//the program demonstrates if/else statement
public class IfElse {
	public static void main(String[] args) {
	    int x = 5;
	    int y = 8;

	    // if statement
	    if (x < y) {
		System.out.println("x < y");
	    }

	    // evaluating a boolean expression
	    boolean xLessThanY = x < y;
	    System.out.println("xLessThanY = " + xLessThanY);

	    // if/else statement
	    if (x == 4) {
		System.out.println("x is 4");
	    } else {
		System.out.println("x is not 4");
	    }

	    int z = 0;
	    // boolean expressions; nested if/else
	    if ( x == 4 || y < 10) {
		if ( x <= 5 && y >= 8.05) {
		    z = 1;
		} else {
		    z = 2;
		}
	    } else {
		z = 3;
	    }
	    System.out.println("z = " + z);
	}
}
Download the following classes into your java program directory: CharStack.class and StackException.class.

//the program demonstrates a stack used to store characters
//the program demonstrates use of if statement and while loop for
// stacks
public class ShowStack {
	public static void main(String [] args) {
	    // creating a new stack
		CharStack cs = new CharStack();
		// a variable to store stack characters
		char c;

		cs.push('!');
		cs.push('y');
		cs.push('e');
		cs.push('h');

		c = cs.pop();
		if (cs.isEmpty()) {
		    System.out.println("Stack is empty");
		}
		// push c back onto the stack
		cs.push(c);

		// the loop continues until the stack becomes empty
		while (!cs.isEmpty()) {
		    c = cs.pop();
		    System.out.print(c); 
		}

		System.out.println(); // new line
	}
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.