Java 0101
Java 0101
§ The following are the organizations that are using Java and they need good Java
Programmers:
§ EGA
§ TRA
§ TAMISEMI
§ LATRA
§ ATCL
§ TRC
§ Ministry of Finance and Planning
§ 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 the Virtual
Machine (JVM) on whichever platform it is being run on.
§ Simple − Java is designed to be easy to learn. If you understand the
basic concept of OOP Java, it would be easy to master.
§ Secure − With Java's secure feature it enables to develop virus-free,
tamper-free systems. Authentication techniques are based on public-key
encryption.
§ Architecture-neutral − Java compiler generates an architecture-neutral object
file format, which makes the compiled code executable on many processors,
with the presence of Java runtime system.
§ Portable − Being architecture-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.
§ 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 perform many tasks simultaneously. This design feature
allows the developers to construct interactive applications that can run
smoothly.
§ 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 light-weight
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.
§ Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behavior such as wagging their tail, barking, eating. An
object is an instance of a class.
§ Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
§ 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.
§ Polymorphism
§ Inheritance
§ Encapsulation
§ Abstraction
§ Classes
§ Objects
§ Instance
§ Method
§ Message Passing
§ 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 initialized when the class is instantiated.
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
§ A constructor is a function that creates and initializes an object
§ It has the same name as its class and is syntactically similar to a method.
However, constructors have no explicit return type.
§ Typically, you will use a constructor to give initial values to the instance
variables defined by the class, or to perform any other start-up procedures
required to create a fully formed object.
§ All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor that initializes all member
variables to zero. However, once you define your own constructor, the default
constructor is no longer used.
class ClassName {
ClassName() {
}
}
1. No argument Constructors
2. Parameterized Constructors
§ As the name specifies the no argument constructors of Java does not
accept any parameters instead, using these constructors the instance
variables of a method will be initialized with fixed values for all objects.
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.num + " " + t2.num);
}
}
§ Most often, you will need a constructor that accepts one or more parameters.
§ Parameters are added to a constructor in the same way that they are added to
a method, just declare them inside the parentheses after the constructor's
name.
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
§ An object is created from a class.
§ In Java, the new keyword is used to create new objects.
§ There are three steps when creating an object from a class −
§ Declaration − A variable declaration with a variable name with an object type.
§ Instantiation − The 'new' keyword is used to create the object.
§ Initialization − The 'new' keyword is followed by a call to a constructor.
§ This call initializes the new object.
§ Instance variables and methods are accessed via created objects.
§ To access an instance variable, following is the fully qualified path −
/* First create an object */
ObjectReference = new Constructor();
§ 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.
public class Employee {
// salary variable is a private
static variable private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
WARM UP
§ For our case study, we will be creating two classes. They are Students and
StudentsTest.
§ First open notepad and add the following code.
§ Remember this is the Students class and the class is a public class. Now, save
this source file with the name Students.java.
§ The Students class has four instance variables - name, age, programme and
semester.
§ The class has one explicitly defined constructor, which takes a parameter.
§ The static keyword in Java is used for memory management mainly.
§ We can apply static keyword with variables, methods, blocks and nested
classes.
§ The static keyword belongs to the class than an instance of the class.
The static can be:
i. Variable (also known as a class variable)
ii. Method (also known as a class method)
iii. Block
iv. Nested class
§ If you declare any variable as static, it is known as a static variable.
§ The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
§ The static variable gets memory only once in the class area at the time of class loading.
§ Is used to initialize the static data member.
§ It is executed before the main method at the time of classloading.
class A2{
static{System.out.println("static block ");}
public static void main(String args[]){
System.out.println("Hello main");
}
§
§ There can be a lot of usage of Java this keyword.
§ In Java, this is a reference variable that refers to the current object.
Here is given the 6 usage of java this keyword.
i. this can be used to refer current class instance variable.
ii. this can be used to invoke current class method (implicitly)
iii. this() can be used to invoke current class constructor.
iv. this can be passed as an argument in the method call.
v. this can be passed as argument in the constructor call.
vi. this can be used to return the current class instance from the method.
Warm UP level 1
1. John has a total of 80 marbles. He wants to divide them equally among his 4 friends. Write
a Java program to calculate how many marbles each friend will get. 2.5marks
2. A car rental company charges a base rate of $30 per day plus an additional $0.15 per mile
driven. Write a Java program to calculate the total rental cost for a car if it was driven for 5
days and 400 miles. 2.5marks
3. A farmer wants to fence off a rectangular area to keep her chickens in. She has 200 feet of
fencing material available and wants to maximize the area of the enclosure. Write a Java
program to calculate the dimensions of the enclosure that will maximize its area. 2.5 marks
Warm UP level 1
1. A store is offering a 20% discount on all items. Write a program code to calculate the
discounted price of an item, given its original price. 2.5marks
2. A car is traveling at a speed of 60 km/hr. Write a program code to convert this speed to
miles per hour.. 2.5marks
3. A worker earns Tsh 15 per hour for the first 40 hours of work in a week, and $22.50 per
hour for any additional hours worked. Write a program code to calculate the worker's
weekly pay, given the number of hours worked.. 2.5 marks
4. A bank charges a penalty of Tsh20 if a customer's account balance falls below $100. Write a
program code to calculate the net balance after deducting any penalty, given the account
balance. 2.5 marks
5. A company pays its employees a bonus of Tsh500 if their sales for the month are over
Tsh10,000. Write a program code to calculate the employee's total pay, given their sales for
the month.
Warm UP level 1
1. A store sells items at a discount of 5% if the customer buys more than 10 items. Write a
program code to calculate the discounted price, given the number of items purchased and
their price.. 2.5marks
2. A person wants to invest Tsh10,000 in a savings account, which earns 2% interest per year.
Write a program code to calculate the balance after 5 years 2.5marks
Warm UP level 1
1. Bob wants to convert his temperature in Celsius to Fahrenheit. Write a Java program code
to take input from the user for temperature in Celsius and output the equivalent
temperature in Fahrenheit. 2.5marks
2. A group of friends decides to go on a road trip. They need to calculate the total cost of fuel
for the trip. Write a Java program code to take input from the user for the distance
traveled, cost of fuel per liter, and average mileage of the car, and output the total cost of
fuel for the trip. 2.5marks
3. A grocery store wants to calculate the bill for a customer. Write a Java program code to
take input from the user for the price and quantity of each item purchased, calculate the
total bill amount, and output the final bill with applicable taxes. Consider that the tax rate
is 10% of the total bill amount. 2.5 marks
§ Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
§ It is an important part of OOPs (Object Oriented programming system).
§ The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
§ Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
1. For Method Overriding (so runtime polymorphism can be achieved).
2. For Code Reusability.
Terms used in Inheritance
§ Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
§ Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
§ Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
§ Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.
class Subclass-name extends Superclass-name
{
//methods and fields
}
§ A class which is inherited is called a parent or superclass, and the new class is called child or
subclass.
class Employee{
float salary=200000;
}
class Programmer extends Employee{
int bonus=50000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
§ On the basis of class, there can be three types of inheritance in java:
1. Single
2. Multilevel
3. Hierarchical.
§ In java programming, multiple and hybrid inheritance is supported through interface only.
§
§ When a class inherits another class, it is known as a single inheritance.
§ In the example given below, Dog class inherits the Animal class, so there is the single inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
§ When there is a chain of inheritance, it is known as multilevel inheritance.
§ As you can see in the example given below, BabyDog class inherits the Dog class which again
inherits the
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
§ Animal class, so there is a multilevel inheritance.
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
§ When two or more classes inherits a single class, it is known as hierarchical inheritance.
§ In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
§ is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to
a child class object.
§ Any Java object that can pass more than one IS-A test is considered to be
polymorphic.
§ In Java, all Java objects are polymorphic since any object will pass the IS-A test
for their own type and for the class Object.
§ It is important to know that the only possible way to access an object is
through a reference variable.
§ A reference variable can be of only one type. Once declared, the type of a
reference variable cannot be changed.
§ The reference variable can be reassigned to other objects provided that it is
not declared final. The type of the reference variable would determine the
methods that it can invoke on the object.
§ A reference variable can refer to any object of its declared type or any
subtype of its declared type.
§ A reference variable can be declared as a class or interface type.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
§ Now, the Deer class is considered to be polymorphic since this has multiple
inheritance. Following are true for the above examples −
§ A Deer IS-A Animal
§ A Deer IS-A Vegetarian
§ A Deer IS-A Deer
§ A Deer IS-A Object
§ When we apply the reference variable facts to a Deer object reference, the
following declarations are legal −
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
§ All the reference variables d, a, v, o refer to the same Deer object in the
heap.
§ If a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.
§ Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
§ Method overriding is used for runtime polymorphism
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
final
§ If you make any class as final, you cannot extend it.
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
final
§ A static final variable that is not initialized at the time of declaration is
known as static blank final variable.
§ It can be initialized only in static block.
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
Runtime
§ Runtime polymorphism or Dynamic Method Dispatch is a process
in which a call to an overridden method is resolved at runtime
rather than compile-time.
§ In this process, an overridden method is called through the
reference variable of a superclass. The determination of the
method to be called is based on the object being referred to by the
reference variable.
1. Upcasting
Occurs when the reference variable of Parent class refers to the object of
Child class
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splendor();//upcasting
b.run();
}
}
Abstraction
§ Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
§ Another way, it shows only essential things to the user and hides the
internal details, for example, sending SMS where you type the text and
send the message. You don't know the internal processing about the
message delivery.
§ Abstraction lets you focus on what the object does instead of how it
does it.
§ There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract
§ A class which is declared with the abstract keyword is known as an
abstract class in Java.
§ It can have abstract and non-abstract methods (method with the
body).
Abstract
§ An abstract class must be declared with an abstract keyword.
§ It can have abstract and non-abstract methods.
§ It cannot be instantiated.
§ It can have constructors and static methods also.
§ It can have final methods which will force the subclass not to
change the body of the method.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Interface
§ An interface in Java is a blueprint of a class. It has static constants
and abstract methods.
§ The interface in Java is a mechanism to achieve abstraction.
§ There can be only abstract methods in the Java interface, not
method body.
§ It is used to achieve abstraction and multiple inheritance in Java.
interface
§ It is used to achieve abstraction.
§ By interface, we can support the functionality of multiple
inheritance.
§ It can be used to achieve loose coupling.
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
§ If a class implements multiple interfaces, or an interface extends
multiple interfaces, it is known as multiple inheritance.
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
inheritance
§ A class implements an interface, but one interface extends another
interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
Spoofing Authenticity
Tampering Integrity
Repudiation Non-repudiability
The college library website will run on a Linux server running Apache. This server
1 will be hardened per the college’s server hardening standard. This includes the
installation of the latest operating system and application security patches.
The database server will be MySQL and it will run on a Linux server. This server
2 will be hardened per the college’s server hardening standard. This will include
the installation of the latest operating system and application security patches.
3
The connection between the web server and the database server will be over a
private network.
4 The web server is behind a firewall and the only communication available is TLS.
Entry Points
§ Entry points define the interfaces through which potential
attackers can interact with the application or supply it with data.
§ In order for a potential attacker to attack an application, entry
points must exist. Entry points in an application can be layered.
§ For example, each web page in a web application may contain
multiple entry points.
§ Entry points show where data enters the system (i.e. input fields,
methods) and exit points are where it leaves the system (i.e.
dynamic output, methods), respectively.
§ Entry and exit points define a trust boundary
Entry Points
§ Entry points should be documented as follows:
§ ID: A unique ID assigned to the entry point. This will be used to cross-
reference the entry point with any threats or vulnerabilities that are
identified. In the case of layered entry points, a major.minor notation
should be used.
§ Name: A descriptive name identifying the entry point and its purpose.
§ Description: A textual description detailing the interaction or processing
that occurs at the entry point.
§ Trust Levels: The level of access required at the entry point. These will
be cross-referenced with the trust levels defined later in the document
ENTRY POINTS
ID Name Description Trust Levels
Assets relating to
Library Users and students, faculty
1
Librarian members, and
librarians.
EXTERNAL ENTITY
§ The process shape represents a task that handles data within the
application. The task may process the data or perform an action
based on the data.
Process
§ The process shape represents a task that handles data within the
application. The task may process the data or perform an action
based on the data.
Multiple
Process
§ The data store shape is used to represent locations where
data is stored. Data stores do not modify the data, they
only store data.
Data Store
§ The data flow shape represents data movement within the
application. The direction of the data movement is represented by
the arrow.
§ The privilege boundary (or trust boundary) shape is used to
represent the change of trust levels as the data flows through the
application. Boundaries show any location where the level of trust
changes.
THREAT MODELING METHODOLOGIES
STRIDE:
§ This is a threat modeling methodology developed by
Microsoft that stands for Spoofing, Tampering,
Repudiation, Information Disclosure, Denial of Service,
and Elevation of Privilege.
§ It helps organizations identify threats in each of these
categories and design countermeasures to mitigate them.
THREAT MODELING METHODOLOGIES
PASTA:
§ The Process for Attack Simulation and Threat Analysis (PASTA) is a
threat modeling methodology that follows a structured approach
to identify potential security threats and vulnerabilities in a system
using various techniques like data flow diagrams and vulnerability
assessments
THREAT MODELING METHODOLOGIES
DREAD:
§ This is another methodology developed by Microsoft that stands
for Damage potential, Reproducibility, Exploitability, Affected
users, and Discoverability.
§ It helps organizations prioritize threats based on the severity of
their impact and the likelihood of them occurring.
THREAT MODELING METHODOLOGIES
Trike:
§ This threat modeling methodology is based on the idea that a
threat is a function of the attack surface, the attacker skill, and the
attacker motivation.
§ It uses a structured approach that involves identifying assets,
attackers, attack vectors, and then assessing the risks associated
with each.
Web Application Attacks & Countermeasures To
Secure Web Applications