Cir 205 Notes
Cir 205 Notes
CASE STUDIES: The Standard Library, the STL - its use and its internals.
Mode of Delivery
Lecturers, Class Programming Exercise, Group Exercises, Focused Group Discussions
Instructional Materials and Equipment
Whiteboard, Whiteboard Maker Pens, Projector, Computer and Appropriate Programming
Environment Software
Course Assessment
Continuous assessment tests (at least two CATs) 20%
Continuous assessment of the lab. Exercises 10%
End of semester exam; A written paper of 3 hours’ duration 70%
Total 100%
Staff performance
Evaluation forms completed by students
Core Reading Materials
1) Vaskaran, Sarcar (2020) Interactive Object-Oriented Programming in Java. Apress
2) Cay S. Horstmann and Gary Cornell (2013) Core Java, Volume II--Advanced
Features (9th Edition). Prentice Hall,
3) Balagurusamy, E (2013) Object Oriented Programming with C++: 6e. McGraw Hill
4) Nell Dale and Daniel T. Joyce (2011) Object-Oriented Data Structures Using Java.
Cathleen Sether
5) Khandare, S. S., (2011). Programming in Java S. Chand and Company Ltd
Recommended - Journals
1) Journal of Object-Oriented Programming - ACM Digital Library
2) The Journal of Object Technology
3) International Journal of Programming Languages and Applications
Example:
class Myclass{
public static void main(String[] args)
{
System.out.println(“Hello World!”); //Display the string.
}
}
The keyword class begins the class definition for a class named name. The variables and
methods of the class are embraced by the curly brackets that begin and end the class definition
block. The “Hello World” application has no variables and has a single method named main.
CONSTRUCTOR
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor.
There are basically two rules defined for the constructor.
Example
class Main {
int i;
// constructor with no parameter
Main() {
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args) {
// calling the constructor without any parameter
Main obj = new Main();
5|Page Moses Wainaina - 0707691430
System.out.println("Value of i: " + obj.i);
}
}
Output:
Constructor is called
Value of i: 5
- The program has created a constructor Main(). Here, the constructor does not accept any
parameters. Hence, it is known as a no-arg constructor.
Parameterized Constructor
A constructor that has parameters is known as parameterized constructor. If we want to initialize
fields of the class with your own values, then use parameterized constructor.
Example
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
// Now, call methods using reference variables sc, sc1 and sc2 one by one to print output.
sc.display();
sc1.display();
sc2.display();
}
}
Creating an Object
The class provides the blueprints for objects. The objects are the instances of the 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.
Creating an Object
In Java, an object is created from a class. We have already created the class named Main, so now
we can use this to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the
keyword new:
Example
Create an object called "myObj" and print the value of x:
public class Main {
int x = 5;
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
public class Main {
int x = 5;
public static void main(String[] args) {
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.
Syntax
// body
Here,
a, b − formal parameters
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word must
be in uppercase except the first word. For example:
NB: It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.
Method Calling
The method needs to be called for using its functionality. There can be three situations when a
method is called:
A method returns to the code that invoked it when:
Throws an exception
// Class 1
// Helper class
class Addition {
// Initially taking sum as 0
// as we have not started computation
int sum = 0;
// Method
// To add two numbers
public int addTwoInt(int a, int b)
{
// Adding two integer value
sum = a + b;
// Returning summation of two values
return sum;
}
}
// Class 2
// Helper class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating object of class 1 inside main() method
Addition add = new Addition();
// Calling method of above class
// to add two integer
// using instance created
int s = add.addTwoInt(1, 2);
// Printing the sum of two numbers
System.out.println("Sum of two integer values :"
Parameters of a Method
Java methods have parameters (like ingredients) or data that are inputted or passed into the
method. The method uses these parameter values to do the necessary data manipulation and
processing. The method then usually returns the final value after all the necessary data
processing is successfully performed.
Example 2
public class Main {
static void myMethod(String fname) {
System.out.println(fname + " Khan");
}
Returning a Value
By using the parameters that are passed into the method, the method generates a new product
or result. The result returned by the method is also available for use by the Java program to
which this method belongs.
1. public int subtractNumbers(int m, int n) {
2. int p = 0;
3. p = m - n;
4. System.out.println(p);
5. return p;
6. }
In this example, the variable p is returned by the method. The return statement is a Java keyword
return followed by the variable name.
Example
Some Java methods do not return a value; they process a set of tasks without a return value.
When a method does not return a value, it is indicated by the keyword void before the name of
the method.
These are built – in methods in Java, which are instantly available to use in your program. The
Java class library will be present in java archive (i.e., *jar) file with Java Virtual Machine (JVM)
and Java Runtime Environment.
Examples:
Math functions – sqrt(), log(), min(), max(), avg(), sin(), cos(), tan(), round(),etc.
These methods are created by the programmers for their requirement as per the programming
scenario / necessity.
//Create Object
JavaMethods abc = new JavaMethods();
//Call Method
int x = abc.multiply(10, 25, 35);
System.out.println(x);
1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
14. //user defined method
15. public static void findEvenOdd(int num)
16. {
17. //method body
18. if(num%2==0)
19. System.out.println(num+" is even");
22 | P a g e Moses Wainaina - 0707691430
20. else
21. System.out.println(num+" is odd");
22. }
23. }
Output
12 is even
TOPIC 3: Advanced Object Oriented Programming topics: Interfaces & Inner Classes,
Polymorphism and inheritance, memory management internals, handling exception and
safety.
Java Inner Classes (Nested Classes)
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more readable
and maintainable.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Advantage of Java inner classes
1. Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.
Types of Nested classes
There are two types of nested classes non-static and static nested classes. The non-static nested
classes are also known as inner classes.
Output:
class TestOuter1{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestOuter1.Inner obj=new TestOuter1.Inner();
obj.msg();
}
}
Output:
data is 30
In this example, you need to create the instance of static nested class because it has instance
method msg(). But you don't need to create the object of the Outer class because the nested class
is static and static properties, methods, or classes can be accessed without an object
Java static nested class example with a static method
If you have the static member inside the static nested class, you don't need to create an instance
of the static nested class.
TestOuter2.java
public class TestOuter2{
static int data=30;
Output:
data is 30]
Interface in Java
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.
Along with abstract methods, an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.
An interface is similar to a class in the following ways −
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
The byte code of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
However, an interface is different from a class in several ways, including −
An interface does not contain any constructors.
Here,
Language is an interface.
It includes abstract methods: getType() and getVersion().
Implementing an Interface
To use an interface, other classes must implement it. We use the implements keyword to
implement an interface.
Example 1:
interface Polygon {
void getArea(int length, int breadth);
}
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
r1.getArea(5, 6);
}
}
class Main {
public static void main(String[] args) {
ProgrammingLanguage language = new ProgrammingLanguage();
language.getName("Java");
}
}
Output
Programming Language: Java
In the above example, we have created an interface named Language. The interface includes an
abstract method getName().
Here, the ProgrammingLanguage class implements the interface and provides the
implementation for the method.
Here, we know getArea() calculates the area of polygons but the way area is calculated is
different for different polygons. Hence, the implementation of getArea() is independent
of one another.
Interfaces provide specifications that a class (which implements it) must follow.
Now any class that implements the Polygon interface must provide an implementation for
the getArea() method.
Interfaces are also used to achieve multiple inheritance in Java. For example
interface Line {
…
}
interface Polygon {
…
}
In the above example, the Dog class is created by inheriting the methods and fields from
the Animal class.
Here, Dog is the subclass and Animal is the superclass.
Example 1:
class Animal {
class Main {
public static void main(String[] args) {
}
}
Output
My name is Rohu
I can eat
In the above example, we have derived a subclass Dog from superclass Animal. Notice the
statements,
labrador.name = "Rohu";
labrador.eat();
Here, labrador is an object of Dog. However, name and eat() are the members of
the Animal class.
Since Dog inherits the field and method from Animal, we are able to access the field and method
using the object of the Dog.
class Main {
public static void main(String[] args) {
Output
I eat dog food
I can bark
In the above example, the eat() method is present in both the superclass Animal and the
subclass Dog.
Here, we have created an object labrador of Dog.
class Main {
public static void main(String[] args) {
Output
I can eat
I eat dog food
I can bark
In the above example, the eat() method is present in both the base class Animal and the derived
class Dog. Notice the statement,
super.eat();
Here, the super keyword is used to call the eat() method present in the superclass.
We can also use the super keyword to call the constructor of the superclass from the constructor
of the subclass.
Protected Members in Inheritance
In Java, if a class includes protected fields and methods, then these fields and methods are
accessible from the subclass of the class.
Example 4: protected Members in Inheritance
class Animal {
protected String name;
class Main {
public static void main(String[] args) {
labrador.getInfo();
}
}
Output
I am an animal.
My name is Rocky
In the above example, we have created a class named Animal. The class includes a protected
field: name and a method: display().
We have inherited the Dog class inherits Animal. Notice the statement,
labrador.name = "Rocky";
labrador.display();
Here, we are able to access the protected field and method of the superclass using
the labrador object of the subclass.
Why use inheritance?
The most important use of inheritance in Java is code reusability. The code that is present
in the parent class can be directly used by the child class.
Method overriding is also known as runtime polymorphism. Hence, we can achieve
Polymorphism in Java with the help of inheritance.
Types of inheritance
There are five types of inheritance.
1. Single Inheritance
In single inheritance, a single subclass extends from a single superclass. For example
3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses extend from a single superclass. For example,
4. Multiple Inheritance
In multiple inheritance, a single subclass extends from multiple super classes. For example,
Java Polymorphism
Polymorphism is an important concept of object-oriented programming. It simply means more
than one form.
That is, the same entity (method or operator or object) can perform different operations in
different scenarios.
Example
class Polygon {
// renders Square
public void render() {
System.out.println("Rendering Square...");
// renders circle
public void render() {
System.out.println("Rendering Circle...");
}
}
class Main {
public static void main(String[] args) {
Output
Rendering Square...
Rendering Circle...
In the above example, we have created a superclass: Polygon and two
subclasses: Square and Circle. Notice the use of the render() method.
The main purpose of the render() method is to render the shape. However, the process of
rendering a square is different than the process of rendering a circle.
Hence, the render() method behaves differently in different classes. Or, we can say render() is
polymorphic.
Why Polymorphism?
Polymorphism allows us to create consistent code. In the previous example, we can also create
different methods: renderSquare() and renderCircle() to render Square and Circle, respectively.
class Main {
public static void main(String[] args) {
Output:
Java Programming Language
Common English Language
In the above example, we have created a superclass named Language and a subclass named Java.
Here, the method displayInfo() is present in both Language and Java.
The use of displayInfo() is to print the information. However, it is printing different information
in Language and Java.
Based on the object used to call the method, the corresponding information is printed.
This is known as method overloading in Java. Here, the same method will perform different
operations based on the parameter.
Example 3: Polymorphism using method overloading
class Pattern {
class Main {
public static void main(String[] args) {
Pattern d1 = new Pattern();
Output:
**********
##########
In the above example, we have created a class named Pattern. The class contains a method
named display() that is overloaded.
// method with no arguments
display() {...}
EXCEPTION HANDLING:
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
What is exception?
In java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
If an exception occurs, which has not been handled by programmer then program execution gets
terminated and a system generated error message is shown to the user
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
Difference between error and exception
Errors indicate that something severe enough has gone wrong, the application should crash
rather than try to handle the error.
Exceptions are events that occur in the code. A programmer can handle such conditions and take
necessary corrective actions. Few examples:
Null Pointer Exception – When you try to use a reference that points to null.
Arithmetic Exception – When bad data is provided by user, for example, when you try to divide
a number by zero this exception occurs because dividing a number by zero is undefined.
Array Index Out Of Bounds Exception – When you try to access the elements of an array out of
its bounds, for example array size is 5 (which mean it has five elements) and you are trying to
access the 10th element.
Types of exceptions
Advantages of thread
Reduces development time.
Reduces maintenance costs.
Improves the performance of complex applications.
Useful for improving the responsiveness of the user interfaces.
Used in server applications to improve high throughput and resource utilization.
Parallelize tasks.
If a thread cannot use all the computing resources of the CPU (because instructions
depend on each other’s result), running another thread can avoid leaving these idle.
Take advantage of multiprocessor systems
Disadvantages of thread
Multiple threads can interfere with each other when sharing hardware resources such as
caches or translation lookaside buffers (TLBs).
TOPIC 3: Generic programming design patterns, proxy classes, operator overloading etc.
Design Patterns in Java
Design patterns represent the best practices used by experienced object-oriented software
developers. Design patterns are solutions to general problems that software developers faced
during software development. These solutions were obtained by trial and error by numerous
software developers over quite a substantial period of time.
It’s not mandatory to always implement design patterns in your project. Design patterns are not
meant for project development. Design patterns are meant for common problem-solving.
Whenever there is a need, you have to implement a suitable pattern to avoid such problems in the
future. To find out which pattern to use, you just have to try to understand the design patterns
and their purposes. Only by doing that, you will be able to pick the right one
Example:
In many real-world situations, we want to create only one instance of a class. For example, there
can be only one active president of a country at any given time. This pattern is called a Singleton
pattern. Other software examples could be a single DB connection shared by multiple objects as
creating a separate DB connection for every object is costly. Similarly, there can be a single
configuration manager or error manager in an application that handles all problems instead of
creating multiple managers.
Some of the benefits of using design patterns are:
1. Design Patterns are already defined and provides industry standard approach to solve a
recurring problem, so it saves time if we sensibly use the design pattern. There are many
java design patterns that we can use in our java based projects.
2. Using design patterns promotes reusability that leads to more robust and highly
maintainable code. It helps in reducing total cost of ownership (TCO) of the software
product.
private SingletonExample() {
// constructor of the SingletonExample class
}
Proxy classes
Proxy is a design pattern. In Proxy pattern, a proxy object represents a placeholder or surrogate
which provides an interface to outer world to access the functionality of original object. A proxy
object is simply means an object representing another object. Proxies are also known as handles,
surrogates, and wrappers. This type of design pattern comes under structural design pattern.
We create and use proxy objects when we want to add or modify some functionality of an
already existing class. The proxy object is used instead of the original one. Usually, the proxy
objects have the same methods as the original one and in Java proxy classes usually extend the
original class.
Example
The Proxy provides a surrogate or place holder to provide access to an object. A check or bank
draft is a proxy for funds in an account. A check can be used in place of cash for making
purchases and ultimately controls access to cash in the issuer's account.
Types of proxies
Remote proxy:
They are responsible for representing the object located remotely. Talking to the real object
might involve marshaling and unmarshalling of data and talking to the remote object. All that
logic is encapsulated in these proxies and the client application need not worry about them.
Virtual proxy:
These proxies will provide some default and instant results if the real object is supposed to take
some time to produce results. These proxies initiate the operation on real objects and provide a
default result to the application. Once the real object is done, these proxies push the actual data
to the client where it has provided dummy data earlier.
Protection proxy:
If an application does not have access to some resource then such proxies will talk to the objects
in applications that have access to that resource and then get the result back.
Types of proxy
There are four situations in which the Proxy pattern is used.
Virtual proxy
suppose, you want to access a huge file from a database. Since, initialization of a
database client is expensive operation, we will use proxy pattern to instantiate an
instance of database client on first database request by client. After the first request,
proxy will reuse the database client for any future requests by client instead of creating a
new instance of database client every time. This will reduce the duplication of object,
reduce latency to access data from database and save memory.
Operator overloading
Operator overloading is a technique by which operators used in a programming language are
implemented in user-defined types with customized logic that is based on the types of arguments
passed.
Operator overloading facilitates the specification of user-defined implementation for operations
wherein one or both operands are of user-defined class or structure type. This helps user-defined
types to behave much like the fundamental primitive data types. Operator overloading is helpful
in cases where the operators used for certain types provide semantics related to the domain
context and syntactic support as found in the programming language. It is used for syntactical
convenience, readability and maintainability.
For example, using a plus operator + for adding two numbers and concatenating two strings is
the simplest case of operator overloading.
However, Java does not support operator overloading except for one case, string concatenation
using the plus operator.
Here is the complete example.
import java.util.Scanner;
public class OperatorOverloading {
Output:
Enter a string
Hello
Enter another string:
World
Hello World
Enter a number
3
Enter another number
4
7
In this example, the plus operator adds the two integers and concatenates the two strings. It is the
only operator overloading that Java supports.
Other than this, Java does not support user-defined operator overloading. The only part of Java
close to operator overloading is the handling of + for concatenating strings.
It will add the second string at the end of the first string. The example below uses
the concat() method to put together two strings.
import java.util.Scanner;
System.out.println("Enter a string:");
String s1 = sc.next();
String s2 = sc.next();
System.out.println(res);
Output:
Enter a string:
Iterator interface provides the facility of iterating the elements in a forward direction only.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in
which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
1. List <
data-type> list1= new ArrayList<>;
There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
1. ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate
element of different data types. The ArrayList class maintains the insertion order and is non-
synchronized. The elements stored in the ArrayList class can be randomly accessed. Consider the
following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> list=new ArrayList<>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
2. LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is fast because no shifting is required.
Consider the following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
LinkedList<String> al=new LinkedList<>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
3. Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, it is
synchronized and contains many methods that are not the part of Collection framework.
Consider the following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
Vector<String> v=new Vector<>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
63 | P a g e Moses Wainaina - 0707691430
Ashish
Garima
4. Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack.
The stack contains all of the methods of Vector class and also provides its methods like boolean
push(), boolean peek(), boolean push(object o), which defines its properties.
Consider the following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
Stack<String> stack = new Stack<>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Garvit
Amit
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is
used to hold the elements which are about to be processed. There are various classes like
PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
Queue interface can be instantiated as:
1. Queue<String> q1 = new PriorityQueue();
2. Queue<String> q2 = new ArrayDeque();
There are various classes that implement the Queue interface, some of them are given below.
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike
queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Consider the following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
Deque<String> deque = new ArrayDeque<>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It
maintains the insertion order and permits null elements.
Consider the following example.
package testjavacollection1;
import java.util.*;
public class TestJavaCollection1 {
public static void main(String[] args) {
// TODO code application logic here
LinkedHashSet<String> set=new LinkedHashSet<>();
set.add("Ravi");
set.add("Vijay");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Output:
Mango
Apple
Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.
Java AWT components are platform-dependent i.e. components are displayed according to the
view of operating system. AWT is heavy weight i.e. its components are using the resources of
underlying operating system (OS).
Why AWT is platform independent?
Java AWT calls the native platform calls the native platform (operating systems) subroutine for
creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will have different
look and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this
is the platforms have different view for their native components and AWT directly calls the
native subroutine that creates those components.
In simple words, an AWT application will look like a windows application in Windows OS
whereas it will look like a Mac application in the MAC OS.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
APPLETS IN JAVA
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
An applet is a Java class that extends the java.applet.Applet class.
A main() method is not invoked on an applet, and an applet class will not define main().
Applets are designed to be embedded within an HTML page.
74 | P a g e Moses Wainaina - 0707691430
When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.
Right click on the source package under your class, create new java applet under others
Write the following code (Line 1 , line 14,15 and 16) Write click on your code and run your
program
import java.applet.Applet;
1. import java.awt.*;
2. /**
3. *
4. @author HP i7
7. /**
8. Initialization method that will be called after the applet is loaded into
9. the browser.
10. */
11. public void init() {
12. // TODO start asynchronous download of heavy resources
13. }
14. public void paint (Graphics g) {
15. g.drawString ("Hello World", 25, 50);
16. }
17. // TODO overwrite start(), stop() and destroy() methods
18. }
Run your program after writing your applet
Right click on button then events –button- and action performed to write the code
newf obj = new new(); - It is a new form that should be displayed if password and
username is correct
Note: object newf is a another form that is open when the password and username are correct.