Programmer Coding

Stack in java

Stack

 

Stack is a subclass of Vector that applies a typical last-in, first-out stack.

 

Stack only bounds the default creater, which produces an empty stack. Stack includes all the way(method) s circle by Vector, and adds some of its own.

 

Stack( )
Example

The following program illustrates some of the way(method) s accepted by this set −

 

import java.util.*;

 

public class StackDemo {

 

static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println(“push(” + a + “)”); System.out.println(“stack: ” + st);}

static void showpop(Stack st) { System.out.print(“pop -> “); Integer a = (Integer) st.pop(); System.out.println(a);

System.out.println(“stack: ” + st); } public static void main(String args[]) {

Stack st = new Stack(); System.out.println(“stack: ” + st); showpush(st, 42);

showpush(st, 66);

 

showpush(st, 99); showpop(st); showpop(st); showpop(st);

try {

 

showpop(st);

 

} catch (EmptyStackException e) { System.out.println(“empty stack”);

 

}}}

 

This will produce the following result −

Output

stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99)

stack: [42, 66, 99]

pop -> 99

stack: [42, 66]

pop -> 66

stack: [42]

pop -> 42 stack: [ ]

pop -> empty stack

 

Iteration

The Iteration Borderline

 

The Iteration borderline bounds the way(method) s by which you can iteration (obtain one at a time) the elements in a set of objects.

The way(method) s said by Iteration are summarized in the following table −

 

Sr.No.                                                            Way(method)  & Description

 

 

  • boolean hasMoreElements( )

When applied, it must return true while there are still more elements to extract, and false when all the elements have been iteration.

 

2                        Object nextElement( )

This returns the next object in the iteration as a generic Object footnote.

Example

 

Following is an example showing usage of Iteration.

import java.util.Vector; import java.util.Enumeration;

public class EnumerationTester {

 

public static void main(String args[]) { Enumeration days;

Vector dayNames = new Vector(); dayNames.add(“Sunday”); dayNames.add(“Monday”); dayNames.add(“Tuesday”); dayNames.add(“Wednesday”); dayNames.add(“Thursday”); dayNames.add(“Friday”); dayNames.add(“Saturday”);

days = dayNames.elements(); while (days.hasMoreElements()) {

System.out.println(days.nextElement());

 

} }}

This will produce the following result −

Output

 

Sunday Monday Tuesday Wednesday Thursday Friday Saturday

 

Iterator

 

It is a universal iterator as we can apply it to any Set object. By using Iterator, we can apply both read and remove missions. It is improved version of Iteration with additional                          convenience of remove-ability of a element.

Iterator must be used whenever we want to iteration elements in all Set structure applied borderlines like Set, List, Queue, Deque and also in all applied classes of Map borderline. Iterator is the only cursorily free-for-all for entire set structure.

Iterator object can be produced by calling iterator() way(method)  present in Set borderline.

// Here “c” is any set of object. itr is of

// type Iterator interface and refers to “c” Iterator itr = c.iterator();

// Returns true if the iteration has more elements

public boolean hasNext();

 

// Returns the next element in the iteration

// It throws NoSuchElementException if no more

// element present

public Object next();

 

// Remove the next element in the iteration

// This method can be called only once per call

// to next()

 

public void remove();

Iterator borderline bounds three way(method) s:

remove() way(method)  can throw two exceptions

  • UnacceptedOperationException : If the remove operation is not accepted by this iterator
  • IllegalStateException : If the next way(method) has not yet been called, or the remove way(method)  has already been called after the last call to the next way(method)

Limitations of Iterator:

  • Only forward direction iterating is
  • Replacement and addition of new element is not accepted by
java.util.Random
  • For using this class to produce random numbers, we have to first produce an instance of this class and then produce way(method) s such as nextInt(), nextDouble(), nextLong() etc using that
  • We can produce random numbers of types integers, float, double, long, booleans using this
  • We can pass arguments to the way(method) s for placing an upper bound on the range of the numbers to be produced. For example, nextInt(6) will produce numbers in the range 0 to 5 both
// A Java program to demonstrate random number generation

// using java.util.Random; import java.util.Random;

 

public class produceRandom{

 

public static void main(String args[])

{

// produce instance of Random class Random rand = new Random();

 

// Produce random integers in range 0 to 999 int rand_int1 = rand.nextInt(1000);

int rand_int2 = rand.nextInt(1000);

 

// Print random integers System.out.println(“Random Integers: “+rand_int1); System.out.println(“Random Integers: “+rand_int2);

 

// Produce Random doubles

double rand_dub1 = rand.nextDouble(); double rand_dub2 = rand.nextDouble();

 

// Print random doubles

System.out.println(“Random Doubles: “+rand_dub1); System.out.println(“Random Doubles: “+rand_dub2);

}}

Output:

Random Integers: 547

Random Integers: 126

Random Doubles: 0.8369779739988428

Random Doubles: 0.5497554388209912

Java Scanner class

 

There are various way(method) s to read input from the keyboard, the java.util.Scanner class is one of them. The Java Scanner class breaks the input into landmarks using a delimiter that is whitespace bydefault. It gives a lot of way(method) s to read and parse various primitive values.

 

Java Scanner class is widely used to parse text for string and primitive types using regular expression.

 

Java Scanner class expand Object class and applies Iterator and Closeable borderlines.

 

Commonly used way(method) s of Scanner class

 

 

Method                                      Description

There is a list of commonly used Scanner class way(method) s:

 

 

public String next()

 

it returns the next landmark from the scanner.

public String nextLine() it moves the scanner position to the next line and returns the value as a string.
public byte nextByte() it scans the next landmark as a byte.

 

public short nextShort() it scans the next landmark as a short value.
public int nextInt() it scans the next landmark as an int value.
public long nextLong() it scans the next landmark as a long value.
public float nextFloat() it scans the next landmark as a float value.
public                              double nextDouble() it scans the next landmark as a double value.

 

Java Scanner Example to get input from console

 

Let’s see the simple example of the Java Scanner class which reads the int, string and double value as an input:

 

import java.util.Scanner;

class ScannerTest{

public static void main(String args[]){ Scanner sc=new Scanner(System.in); System.out.println(“Enter your rollno”); int rollno=sc.nextInt(); System.out.println(“Enter your name”); String name=sc.next(); System.out.println(“Enter your fee”); double fee=sc.nextDouble();

System.out.println(“Rollno:”+rollno+” name:”+name+” fee:”+fee); sc.close();

} }  Output:

Enter your rollno 111

Enter your name ram

Enter 450000

Rollno:111 name:ram fee:450000

 

Java Calendar Class

 

Java Calendar class is an conceptual class that gives way(method) s for converting date between a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It inherits Object class and applies the Comparable borderline.

Java Calendar class announcement

 

Let’s see the announcement of java.util.Calendar class.

 

  1. public conceptual class Calendar expand Object
  2. applies Serializable, Cloneable, Comparable<Calendar>

 

Java Calendar Class Example

 

import java.util.Calendar;

public class CalendarExample1 {

public static void main(String[] args) { Calendar calendar = Calendar.getInstance();

System.out.println(“The current date is : ” + calendar.getTime()); calendar.add(Calendar.DATE, -15);

System.out.println(“15 days ago: ” + calendar.getTime()); calendar.add(Calendar.MONTH, 4);

System.out.println(“4 months later: ” + calendar.getTime()); calendar.add(Calendar.YEAR, 2);

System.out.println(“2 years later: ” + calendar.getTime());

} }

 

Output:

The current date is : Thu Jan 19 18:47:02 IST 2017 15 days ago: Wed Jan 04 18:47:02 IST 2017

4 months later: Thu May 04 18:47:02 IST 2017

2 years later: Sat May 04 18:47:02 IST 2019

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top