4. Introduction to Java
• Developed by Sun Microsystems (has merged
into Oracle Corporation later)
• Initiated by James Gosling
• Released in 1995
• Java has 3 main versions as Java SE, Java EE
and Java ME
5. Features of Java
Object Oriented
Platform independent
Simple
Secure
Portable
Robust
Multi-threaded
Interpreted
High Performance
6. What you can create by Java?
• Desktop (GUI) applications
• Enterprise level applications
• Web applications
• Web services
• Java Applets
• Mobile applications
11. Java Virtual Machine (JVM)
1. When Java source code (.java files) is
compiled, it is translated into Java bytecodes
and then placed into (.class) files.
2. The JVM executes Java bytecodes and run
the program.
Java was designed with a concept of write once and
run anywhere. Java Virtual Machine plays the
central role in this concept.
12. Basic Rules to Remember
Java is case sensitive…
Hello not equals to hello
13. Basic Rules to Remember
Class name should be a single word and it
cannot contain symbols and should be started
with a character…
Wrong class name Correct way
Hello World HelloWorld
Java Window Java_Window
3DUnit Unit3D
“FillForm” FillForm
14. public class MyFirstApp{
public static void main(String[] args){
System.out.println("Hello World");
}
}
Basic Rules to Remember
Name of the program file should exactly match
the class name...
Save as MyFirstApp.java
15. Basic Rules to Remember
Main method which is a mandatory part of
every java program…
public class MyFirstApp{
public static void main(String[] args){
System.out.println("Hello World");
}
}
16. Basic Rules to Remember
Tokens must be separated by Whitespaces
Except ( ) ; { } . [ ] + - * / =
public class MyFirstApp{
public static void main(String[] args){
System.out.println("Hello World");
}
}
21. Primitive Data Types in Java
Keyword Type of data the variable will store Size in memory
boolean true/false value 1 bit
byte byte size integer 8 bits
char a single character 16 bits
double double precision floating point decimal number 64 bits
float single precision floating point decimal number 32 bits
int a whole number 32 bits
long a whole number (used for long numbers) 64 bits
short a whole number (used for short numbers) 16 bits
22. Variable Declaration in Java
Variable declaration
type variable_list;
Variable declaration and initialization
type variable_name = value;
23. Variable Declaration in Java
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints,
initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation
of pi.
char x = 'x'; // the variable x has the value 'x'.
26. Java Objects
Dog myPet = new Dog(); //creating an object
//Assigning values to Attributes
myPet.name = “Scooby”;
myPet.color = “Brown”;
//calling method
myPet.bark();
27. Methods
Method is a group of statements to perform a
specific task.
• Methods with Return Value
• Methods without Return Value
28. Methods with Return Value
public int num1, int num2){
int result;
if (num1 > num2){
result = num1;
}else{
result = num2;
}
return result;
}
Access modifier
Return type
Method name
parameters
Return value
Method body
29. Methods without Return Value
public void {
System.out.println(“your text: “ + txt)
}
Access modifier
Void represents no return value
Method name
parameter
Method
body
30. Constructors
• Each time a new
object is created the
constructor will be
invoked
• Constructor are
created with class
name
• There can be more
constructors
distinguished by their
parameters
class Dog{
String name;
public Dog(String name){
this.name = name;
}
}
//creating an object from Dog class
Dog myDog = new Dog(“brown”);
Constructor
String Parameter
String Argument
31. Variables in a Class
Variables in a Class can be categorize into
three types
1. Local Variables
2. Instance Variables
3. Static/Class Variables
32. Local Variables
• Declared in methods,
constructors, or blocks.
• Access modifiers cannot
be used.
• Visible only within the
declared method,
constructor or block.
• Should be declared with
an initial value.
public class Vehicle{
int number;
String color;
static String model;
void Drive(){
int speed = 100;
System.out.print(“vehicle
is driving in “ + speed +
“kmph”);
}
}
33. Instance Variables
• Declared in a class, but
outside a method,
constructor or any block.
• Access modifiers can be
given.
• Can be accessed directly
anywhere in the class.
• Have default values.
• Should be called using an
object reference to access
within static methods and
outside of the class.
public class Vehicle{
int number;
String color;
static String model;
void Drive(){
int speed = 100;
System.out.print(“vehicle
is driving in “ + speed +
“kmph”);
}
}
34. Static/Class Variables
public class Vehicle{
int number;
String color;
static String model;
void Drive(){
int speed = 100;
System.out.print(“vehicle
is driving in “ + speed +
“kmph”);
}
}
• Declared with the static
keyword in a class, but
outside a method,
constructor or a block.
• Only one copy for each
class regardless how
many objects created.
• Have default values.
• Can be accessed by
calling with the class
name.
36. Arithmetic Operators
Operator Description Example
+ Addition A + B will give 30
- Subtraction A - B will give -10
* Multiplication A * B will give 200
/ Division B / A will give 2
% Modulus B % A will give 0
++ Increment B++ gives 21
-- Decrement B-- gives 19
A = 10, B = 20
37. Assignment Operators
Operator Example
= C = A + B will assign value of A + B into C
+= C += A is equivalent to C = C + A
-= C -= A is equivalent to C = C - A
*= C *= A is equivalent to C = C * A
/= C /= A is equivalent to C = C / A
%= C %= A is equivalent to C = C % A
38. Comparison Operators
Operator Example
== (A == B) is false.
!= (A != B) is true.
> (A > B) is false.
< (A < B) is true.
>= (A >= B) is false.
<= (A <= B) is true.
A = 10, B = 20
39. Logical Operators
Operator Name Example
&& AND (A && B) is False
|| OR (A || B) is True
! NOT !(A && B) is True
A = True, B = False
45. If… Else if… Else Statement
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition
is true.
}
47. Nested If Statement
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is
true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is
true
}
}
62. Non Access 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.
64. Interfaces
• An interface contains a
collection of abstract
methods that a class
implements.
• Interfaces states the names
of methods, their return
types and arguments.
• There is no body for any
method in interfaces.
• A class can implement
more than one interface at
a time.
interface Vehicle{
public void Drive(int speed);
public void Stop();
}
public class Car implements Vehicle{
public void Drive(int kmph){
System.out.print(“Vehicle is driving
in ” + kmph + “kmph speed”);
}
public void Stop(){
System.out.print(“Car stopped!”);
}
}
66. Inheritance
class Vehicle{
//attributes and methods
}
class Car extends Vehicle{
//attributes and methods
}
class Van extends Vehicle{
//attributes and methods
}
Vehicle
Car Van
67. Method Overloading
public class Car{
public void Drive(){
System.out.println(“Car is driving”);
}
public void Drive(int speed){
System.out.println(“Car is driving in ” + speed +
“kmph”);
}
}
68. Method Overriding
class Vehicle{
public void drive(){
System.out.println(“Vehicle is driving”);
}
}
class Car extends Vehicle{
public void drive(){
System.out.println(“Car is driving”);
}
}
69. Polymorphism
class Animal{
public void Speak(){
}
}
class Cat extends Animal{
public void Speak(){
System.out.println(“Meow");
}
}
class Dog extends Animal{
public void Speak(){
System.out.println(“Woof");
}
}
class Duck extends Animal{
public void Speak(){
System.out.println(“Quack");
}
}
Animal d = new Dog();
Animal c = new Cat();
Animal du = new Duck();
d.Speak();
c.Speak();
du.Speak();
72. Strings
• String is a sequence of characters
• In java, Strings are objects.
• Strings have been given some features to be
looked similar to primitive type.
String <variable name> = new String(“<value>”);
or
String <variable name> = “<value>”;
76. StringBuffer Class Methods
public StringBuffer append(String s)
Updates the value of the object that invoked the method. The method
takes boolean, char, int, long, Strings etc.
public StringBuffer reverse()
The method reverses the value of the StringBuffer object that invoked
the method.
public delete(int start, int end)
Deletes the string starting from start index until end index.
public insert(int offset, int i)
This method inserts an string s at the position mentioned by offset.
replace(int start, int end, String str)
This method replaces the characters in a substring of this StringBuffer
with characters in the specified String.
77. StringBuilder Class
The java.lang.StringBuilder class is mutable
sequence of characters. This provides an API
compatible with StringBuffer, but with no
guarantee of synchronization.
StringBuilder <variable name> = new StringBuilder("
<value> ");
78. StringBuilder Class Methods
StringBuilder append(String str)
This method appends the specified string to this character sequence.
StringBuilder reverse()
This method causes this character sequence to be replaced by the
reverse of the sequence.
StringBuilder delete(int start, int end)
This method removes the characters in a substring of this sequence.
StringBuilder insert(int offset, String str)
This method inserts the string into this character sequence.
StringBuilder replace(int start, int end, String str)
This method replaces the characters in a substring of this sequence
with characters in the specified String.
79. Comparison
String Class StringBuffer Class StringBuilder Class
Immutable Mutable Mutable
Not thread safe Thread safe Not thread safe
Not synchronized Synchronized Not synchronized
Fast Slow Fast
81. Scanner Class
• The java.util.Scanner is useful for breaking down
formatter input into tokens and translating individual
tokens to their data type.
• A Scanner breaks its input into tokens using a delimiter
pattern, which by default matches whitespace.
Scanner <variable name> = new Scanner(“<value>”);
Scanner <variable name> = new Scanner(new
BufferedReader(new FileReader(“<filename.ext>”));
82. Scanner Class Methods
String next()
This method finds and returns the next complete token from this scanner.
String next(String pattern)
This method returns the next token if it matches the pattern constructed from the
specified string.
boolean hasNext()
This method returns true if this scanner has another token in its input.
String nextLine()
This method advances this scanner past the current line and returns the input that
was skipped.
Scanner useDelimiter(String pattern)
This method sets this scanner's delimiting pattern to a pattern constructed from the
specified String.
int nextInt()
This method scans the next token of the input as an int.
84. Wrapper Classes
• Each of Java's eight primitive data types has a
class dedicated to it known as wrapper classes.
• A wrapper class wraps around a data type and
gives it an object appearance.
• Wrapper classes are part of the java.lang
package, which is imported by default into all
Java programs.
86. Wrapper Classes
Primitive Wrapper Class Constructor Argument
boolean Boolean boolean or String
byte Byte byte or String
char Character char
int Integer int or String
float Float float, double or String
double Double double or String
long Long long or String
short Short short or String
87. Wrapper Class Methods
Method Purpose
parseInt(s) Returns a signed decimal integer value equivalent to string s
toString(i) Returns a new String object representing the integer i
byteValue() Returns the value of this Integer as a byte
doubleValue() Returns the value of this Integer as an double
floatValue() Returns the value of this Integer as a float
intValue() Returns the value of this Integer as an int
shortValue() Returns the value of this Integer as a short
longValue() Returns the value of this Integer as a long
int compareTo(int i) Compares the numerical value of the invoking object with
that of i. Returns 0, minus value or positive value
static int compare(int
num1, int num2)
Compares the values of num1 and num2. Returns 0, minus
value or positive value
boolean equals(Object
intObj)
Returns true if the invoking Integer object is equivalent to
intObj. Otherwise, it returns false
89. AutoBoxing
Autoboxing is the automatic conversion that the
Java compiler makes between the primitive
types and their corresponding object wrapper
classes.
94. What is a Collection?
• An object that groups multiple elements into a
single unit.
• Used to store, retrieve, manipulate, and
communicate aggregate data.
• They represent data items that form a natural
group, such as a mail folder (collection of letters),
or a telephone directory (a mapping of names to
phone numbers).
95. Java Collection Framework
Java Collection Framework is a unified architecture for
representing and manipulating collections.
It contain the following:
• Interfaces: Abstract data types that represent
collections.
• Implementations: Concrete implementations of the
collection interfaces.
• Algorithms: Methods that perform useful
computations.
96. Interfaces on Collection Framework
The Collection Interface
This enables you to work with groups of objects; it is at the top of the collections hierarchy.
The List Interface
This extends Collection and an instance of List stores an ordered collection of elements.
The Set
This extends Collection to handle sets, which must contain unique elements
The SortedSet
This extends Set to handle sorted sets
The Map
This maps unique keys to values.
The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner class of Map.
The SortedMap
This extends Map so that the keys are maintained in ascending order.
The Enumeration
This is legacy interface and defines the methods by which you can enumerate (obtain one at a time) the
elements in a collection of objects.
97. Implementations on Collection Framework
AbstractCollection
Implements most of the Collection interface.
AbstractList
Extends AbstractCollection and implements most of the List interface.
AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential rather than random access of its
elements.
LinkedList
Implements a linked list by extending AbstractSequentialList.
ArrayList
Implements a dynamic array by extending AbstractList.
AbstractSet
Extends AbstractCollection and implements most of the Set interface.
HashSet
Extends AbstractSet for use with a hash table.
LinkedHashSet
Extends HashSet to allow insertion-order iterations.
98. Implementations on Collection Framework
TreeSet
Implements a set stored in a tree. Extends AbstractSet.
AbstractMap
Implements most of the Map interface.
HashMap
Extends AbstractMap to use a hash table.
TreeMap
Extends AbstractMap to use a tree.
WeakHashMap
Extends AbstractMap to use a hash table with weak keys.
LinkedHashMap
Extends HashMap to allow insertion-order iterations.
IdentityHashMap
Extends AbstractMap and uses reference equality when comparing documents.
99. Implementations on Collection Framework
Vector
This implements a dynamic array. It is similar to ArrayList, but with some differences.
Stack
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Dictionary
Dictionary is an abstract class that represents a key/value storage repository and operates much like
Map.
Hashtable
Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.
Properties
Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and
the value is also a String.
BitSet
A BitSet class creates a special type of array that holds bit values. This array can increase in size as
needed.
100. Algorithms on Collection Framework
static int binarySearch(List list, Object value)
Searches for value in list. The list must be sorted. Returns the position
of value in list, or -1 if value is not found.
static Object max(Collection c)
Returns the maximum element in c as determined by natural ordering.
The collection need not be sorted.
static Object min(Collection c)
Returns the minimum element in c as determined by natural ordering.
static void sort(List list, Comparator comp)
Sorts the elements of list as determined by comp.
static void shuffle(List list)
Shuffles the elements in list.
102. Exceptions
An exception is a problem that arises during the
execution of a program. An exception can occur
for many different reasons, like:
• 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
104. Exception Categories
• Checked exceptions: Cannot simply be
ignored at the time of compilation.
• Runtime exceptions: Ignored at the time of
compilation.
• Errors: Problems that arise beyond the control
of the user or the programmer.
105. Handling and Throwing Exceptions
try {
//Protected code
} catch(ExceptionName var) {
//Catch block
} finally {
//The finally block always executes
}
public void Show() throws <ExceptionName> {
throw new <ExceptionName>;
}
You can…
handle
Exceptions
by using try
catch blocks
or
throw
Exceptions
106. Declaring you own Exception
• All exceptions must be a child of Throwable.
• If you want to write a checked exception, you
need to extend the Exception class.
• If you want to write a runtime exception, you
need to extend the RuntimeException class.
There are no any static outer classes in java but “Static inner Classes”
public class A {
public static void main(String[] args) {
B b = new B();
}
public static class B {
}
}
Because class B is declared static you can explicitly instantiate as:
B b = new B();
Note if class B wasn't declared static to make it stand alone, an instance object call would've looked like this:
A a= new A();
B b = a.new B();
Static methods can be called without instantiating an object / Static methods can be called outside of the class directly with the class name
-----------------------------------------------------------------------------
Final classes can not be extended
-----------------------------------------------------------------------------
Synchronized methods demo program
class show{
public synchronized void display(int n){
try{
for(int i=1; i<=5; i++){
System.out.println(i*n);
Thread.sleep(1000);
}
}catch(Exception e){
}
}
}
class rasan implements Runnable{
int n;
show s;
public rasan(int n, show s){
this.n = n;
this.s = s;
}
public void run(){
s.display(n);
}
}
public class MySync {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
show sh = new show();
Thread x = new Thread(new rasan(10,sh));
Thread y = new Thread(new rasan(100,sh));
x.start();
y.start();
}
}
Void welcome() ///Hello world ///Void welcome(“saman”) ////Hello Saman
package scanxan;
import java.io.*;
import java.util.Scanner;
/**
*
* @author Rasan Samarasinghe
*/
public class ScanXan {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
Scanner s = null;
try{
s = new Scanner(new FileReader("xox.txt"));
//s.useDelimiter(",");
while(s.hasNext()){
System.out.println(s.next());
}
}finally{
if(s != null){
s.close();
}
}
}
}
//-------------------------------------------------------------------
package scansum;
import java.io.*;
import java.util.Locale;
import java.util.Scanner;
/**
*
* @author Rasan Samarasinghe
*/
public class ScanSum{
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
Scanner s= null;
double sum = 0;
try{
s = new Scanner(new BufferedReader(new FileReader("usnumbers.txt")));
s.useLocale(Locale.US);
while(s.hasNext()){
if(s.hasNextDouble()){
sum += s.nextDouble();
}else{
s.next();
}
}
}finally{
s.close();
}
System.out.println(sum);
}
}
In first example both argument of == operator is primitive int type so no autoboxing occurs and since 1==1 it prints true
While in second example during assignment to num1, autoboxing occurs which converts primitive 1 into Integer(1) and when we compare num1==num2 unboxing occurs and Integer(1) is converted back to 1 by calling Integer.intValue() method and since 1==1 result is true. In Third example which is a corner case in autoboxing, both Integer object are initialized automatically due to autoboxing and since Integer.valueOf() method is used to convert int to Integer and it caches object ranges from -128 to 127, it returns same object both time. In short obj1 and obj2 are pointing to same object and when we compare two object with == operator it returns true without any autoboxing. In last example object are explicitly initialized and compared using equality operator , this time == return false because both one and anotherOne reference variables are pointing to different object.
//Collections Interface
package collectionsdemo;
import java.util.*;
/**
*
* @author Rasan Samarasinghe
*/
public class CollectionsDemo {
public static void main(String[] args) {
// TODO code application logic here
List a1 = new ArrayList();
a1.add("rasan");
a1.add("indunil");
a1.add("Samarasinghe");
System.out.print("Arraylist elements:");
System.out.println(a1);
List l1 = new LinkedList();
l1.add("rasan");
l1.add("indunil");
l1.add("samarasinghe");
System.out.println("linkedlist elements: " + l1);
Set s1 = new HashSet();
s1.add("rasan");
s1.add("indunil");
s1.add("samarasinghe");
System.out.println("hashlist elements: "+s1);
Map m1 = new HashMap();
m1.put("rasan","3");
m1.put("indunil", "5");
m1.put("samarasinghe", "4");
System.out.println("Map elements: " + m1);
}
}
/*
Arraylist vs Linkedlist
1. remove operations give good performance in LinkedList compared to ArrayList.
if there is a requirement of frequent addition and deletion in application then LinkedList is a best choice.
2. Search (get method) operations are fast in Arraylist but not in LinkedList
If there are less add and remove operations and more search operations requirement, ArrayList would be your best bet.
Hashset vs Hashmap
HashSet is a set, e.g. {1,2,3,4,5}
In the HashSet, there must be no duplicate elements.
2. HashMap is a key -> value (key to value) map, e.g. {a -> 1, b -> 2, c -> 2, d -> 1}
In the HashMap there must not be duplicate keys, but it may have duplicate values.
*/
//Linked List
package linkedlistdemo;
import java.util.*;
public class LinkedListDemo {
public static void main(String[] args) {
// TODO code application logic here
LinkedList ll = new LinkedList();
ll.add("G");
ll.add("C");
ll.add("D");
ll.add("B");
ll.add("E");
ll.addFirst("A");
ll.addLast("Z");
ll.add(1, "A1");
System.out.println("original contents of ll: "+ll);
ll.remove("B");
ll.remove(4);
System.out.println("contents after deletion: "+ll);
ll.removeFirst();
ll.removeLast();
System.out.println("ll after removing first and last: "+ll);
Object val = ll.get(2);
ll.set(2, val.toString()+val.toString());
System.out.println("ll after change: "+ ll);
}
}
/*
void add(int index, Object element)
Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()).
boolean add(Object o)
Appends the specified element to the end of this list.
boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException if the specified collection is null.
boolean addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null.
void addFirst(Object o)
Inserts the given element at the beginning of this list.
void addLast(Object o)
Appends the given element to the end of this list.
void clear()
Removes all of the elements from this list.
Object clone()
Returns a shallow copy of this LinkedList.
boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
Object get(int index)
Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
Object getFirst()
Returns the first element in this list. Throws NoSuchElementException if this list is empty.
Object getLast()
Returns the last element in this list. Throws NoSuchElementException if this list is empty.
int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
ListIterator listIterator(int index)
Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
Object remove(int index)
Removes the element at the specified position in this list. Throws NoSuchElementException if this list is empty.
boolean remove(Object o)
Removes the first occurrence of the specified element in this list. Throws NoSuchElementException if this list is empty. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
Object removeFirst()
Removes and returns the first element from this list. Throws NoSuchElementException if this list is empty.
Object removeLast()
Removes and returns the last element from this list. Throws NoSuchElementException if this list is empty.
Object set(int index, Object element)
Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()).
int size()
Returns the number of elements in this list.
Object[] toArray()
Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null.
Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array.
*/
//Stack
package stackdemo;
import java.util.*;
public class StackDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Stack st = new Stack();
System.out.println(st);
st.push(new Integer(10));
System.out.println(st);
st.push(new Integer(40));
st.push(new Integer(60));
System.out.println(st);
System.out.println(st.peek());
System.out.println(st.pop());
System.out.println(st);
System.out.println(st.search(new Integer(70)));
}
}
/*
boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.
Object peek( )
Returns the element on the top of the stack, but does not remove it.
Object pop( )
Returns the element on the top of the stack, removing it in the process.
Object push(Object element)
Pushes element onto the stack. element is also returned.
int search(Object element)
Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, .1 is returned.
*/
//Algorithms
package algorithmsdemo;
import java.util.*;
public class AlgorithmsDemo {
public static void main(String[] args) {
// TODO code application logic here
LinkedList ll = new LinkedList();
ll.add(new Integer(-8));
ll.add(new Integer(20));
ll.add(new Integer(-20));
ll.add(new Integer(8));
Comparator r = Collections.reverseOrder();
Collections.sort(ll,r);
Iterator li = ll.iterator();
System.out.print("list ordered in reverse: ");
while(li.hasNext()){
System.out.print(li.next()+" ");
}
System.out.println();
Collections.shuffle(ll);
li = ll.iterator();
System.out.print("list shuffled: ");
while(li.hasNext()){
System.out.print(li.next()+" ");
}
System.out.println();
System.out.println("maximum value: " + Collections.max(ll));
System.out.println("minimum value: " + Collections.min(ll));
}
}