0% found this document useful (0 votes)
45 views

JAVA For Beginners: Main Program

The document discusses arrays in Java. It defines arrays as collections of variables of the same type with a common name. It provides examples of declaring and initializing one-dimensional and two-dimensional arrays and accessing elements. It also demonstrates sorting an array using the bubble sort algorithm and outputting the minimum and maximum values of an array.

Uploaded by

shekharc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

JAVA For Beginners: Main Program

The document discusses arrays in Java. It defines arrays as collections of variables of the same type with a common name. It provides examples of declaring and initializing one-dimensional and two-dimensional arrays and accessing elements. It also demonstrates sorting an array using the bubble sort algorithm and outputting the minimum and maximum values of an array.

Uploaded by

shekharc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

JAVA for Beginners

/* Methods to access alpha. Members of a class can access a


private member of the same class.

*/

void setAlpha(int a) {

alpha = a;

int getAlpha() {

return alpha;

Main Program:

class AccessDemo {

public static void main(String args[]) {

MyClass ob = new MyClass();

ob.setAlpha(-99);

System.out.println("ob.alpha is " + ob.getAlpha());

// You cannot access alpha like this:

// ob.alpha = 10; // Wrong! alpha is private!

// These are OK because beta and gamma are public.

ob.beta = 88;

ob.gamma = 99;

Riccardo Flask 97 | P a g e
JAVA for Beginners

Another example using arrays:

class FailSoftArray {

private int a[]; // reference to array

private int errval; // value to return if get() fails

public int length; // length is public

/* Construct array given its size and the value to

return if get() fails. */

public FailSoftArray(int size, int errv) {

a = new int[size];

errval = errv;

length = size;

// Return value at given index.

public int get(int index) {

if(ok(index)) return a[index];

return errval;

// Put a value at an index. Return false on failure.

public boolean put(int index, int val) {

if(ok(index)) {

a[index] = val;

return true;

return false;

// Return true if index is within bounds.

private boolean ok(int index) {

Riccardo Flask 98 | P a g e
JAVA for Beginners

if(index >= 0 & index < length) return true;

return false;

Main Program:

class FSDemo {

public static void main(String args[]) {

FailSoftArray fs = new FailSoftArray(5, -1);

int x;

// show quiet failures

System.out.println("Fail quietly.");

for(int i=0; i < (fs.length * 2); i++)

fs.put(i, i*10);

for(int i=0; i < (fs.length * 2); i++) {

x = fs.get(i);

if(x != -1) System.out.print(x + " ");

System.out.println("");

// now, handle failures

System.out.println("\nFail with error reports.");

for(int i=0; i < (fs.length * 2); i++)

if(!fs.put(i, i*10))

System.out.println("Index " + i + " out-of-bounds");

for(int i=0; i < (fs.length * 2); i++) {

x = fs.get(i);

if(x != -1) System.out.print(x + " ");

else

Riccardo Flask 99 | P a g e
JAVA for Beginners

System.out.println("Index " + i + " out-of-


bounds");

Predicted Output:

Fail with error reports.

Index 5 out-of-bounds

Index 6 out-of-bounds

Index 7 out-of-bounds

Index 8 out-of-bounds

Index 9 out-of-bounds

0 10 20 30 40 Index 5 out-of-bounds

Index 6 out-of-bounds

Index 7 out-of-bounds

Index 8 out-of-bounds

Index 9 out-of-bounds

Riccardo Flask 100 |


Page
JAVA for Beginners

Arrays and Strings

Arrays
An array can be defined as a collection of variables of the same type defined by a common name,
e.g. an array called Names which stores the names of your class mates:

Names *name , name , name , … nameX+

Arrays in Java are different from arrays in other programming languages because they are
implemented as objects.

One-dimensional Arrays

Declaration: type array-name[ ] = new type[size];

e.g. int sample[] = new int[10];

The following code creates an array of ten integers, fills it up with numbers using a loop and then
prints the content of each location (index) of the array:

class ArrayDemo {

public static void main(String args[]) {

int sample[] = new int[10];

int i;

for(i = 0; i < 10; i = i+1)

sample[i] = i;

for(i = 0; i < 10; i = i+1)

System.out.println("This is sample[" + i + "]: " +

sample[i]);

Predicted Output:

This is sample[0]: 0

This is sample[1]: 1

Riccardo Flask 101 |


Page
JAVA for Beginners

This is sample[2]: 2

This is sample[3]: 3

This is sample[4]: 4

This is sample[5]: 5

This is sample[6]: 6

This is sample[7]: 7

This is sample[8]: 8

This is sample[9]: 9

The following program contains two loops used to identify the smallest and the largest value stored
in the array:

class MinMax {

public static void main(String args[]) {

int nums[] = new int[10];

int min, max;

nums[0] = 99;

nums[1] = -10;

nums[2] = 100123;

nums[3] = 18;

nums[4] = -978;

nums[5] = 5623;

nums[6] = 463;

nums[7] = -9;

nums[8] = 287;

nums[9] = 49;

min = max = nums[0];

for(int i=1; i < 10; i++) {

if(nums[i] < min) min = nums[i];

Riccardo Flask 102 |


Page
JAVA for Beginners

if(nums[i] > max) max = nums[i];

System.out.println("min and max: " + min + " " +


max);

Predicted Output:

min and max: -978 100123

Sorting an Array The Bubble Sort


The Bubble sort is one type, the simplest, of sorting algorithms. It can be used to sort data stored in
arrays but it is not ideal when the size of the array to sort is large.

class Bubble {

public static void main(String args[]) {

int nums[] = { 99, -10, 100123, 18, -978,

5623, 463, -9, 287, 49 };

int a, b, t;

int size;

size = 10; // number of elements to sort

// display original array

System.out.print("Original array is:");

for(int i=0; i < size; i++)

System.out.print(" " + nums[i]);

System.out.println();

// This is the Bubble sort.

for(a=1; a < size; a++)

for(b=size-1; b >= a; b -) {

Riccardo Flask 103 |


Page
JAVA for Beginners

if(nums[b-1] > nums[b]) { // if out of order

// exchange elements

t = nums[b-1];

nums[b-1] = nums[b];

nums[b] = t;

// display sorted array

System.out.print("Sorted array is:");

for(int i=0; i < size; i++)

System.out.print(" " + nums[i]);

System.out.println();

Predicted Output:

Original array is: 99 -10 100123 18 -978 5623 463 -9 287 49

Sorted array is: -978 -10 -9 18 49 99 287 463 5623 100123

Two-Dimensional Arrays:

A two dimensional array is like a list of one-dimensional arrays. Declaration is as follows:

int table[][] = new int[10][20];

This would create a table made up of 10 rows (index: 0 to 9) and 20 columns (index: 0 to 19). The
following code creates a table, 3 rows by 4 columns, and fills it up woth numbers from 1 to 12. Note
that at index [0][0] = 1, [0][1] = 2, [0][2] = 3, [0][3] = 4, [1][0] = 5, etc.

class TwoD {

public static void main(String args[]) {

Riccardo Flask 104 |


Page
JAVA for Beginners

int t, i;

int table[][] = new int[3][4];

for(t=0; t < 3; ++t) {

for(i=0; i < 4; ++i) {

table[t][i] = (t*4)+i+1;

System.out.print(table[t][i] + " ");

System.out.println();

Different syntax used to declare arrays:


Consider the following: type[ ] var-name;

The square brackets follow the type specifier, not the name of the array variable. For example, the
following two declarations are equivalent:

int counter[] = new int[3];

int[] counter = new int[3];

The following declarations are also equivalent:

char table[][] = new char[3][4];

char[][] table = new char[3][4];

This alternative declaration form offers convenience when declaring several arrays at the same time.

int[] nums, nums2, nums3; // create three arrays

This creates three array variables of type int. It is the same as writing:

int nums[], nums2[], nums3[]; // also, create three arrays

The alternative declaration form is also useful when specifying an array as a return type for a
method:

int[] someMeth( ) { ...

Riccardo Flask 105 |


Page
JAVA for Beginners

This declares that someMeth( ) returns an array of type int.

Array References:

Consider a particular array, nums1, and another array, nums2 and at one point in the code we assign
one array reference to the other, i.e. nums2 = nums1. Then every action on nums2 will be as if it
were on nums1 (nums2 reference is lost).

class AssignARef {

public static void main(String args[]) {

int i;

int nums1[] = new int[10];

int nums2[] = new int[10];

for(i=0; i < 10; i++)

nums1[i] = i;

for(i=0; i < 10; i++)

nums2[i] = -i;

System.out.print("Here is nums1: ");

for(i=0; i < 10; i++)

System.out.print(nums1[i] + " ");

System.out.println();

System.out.print("Here is nums2: ");

for(i=0; i < 10; i++)

System.out.print(nums2[i] + " ");

System.out.println();

nums2 = nums1; // nums2 is now nums1

System.out.print("Here is nums2 after assignment:


");

for(i=0; i < 10; i++)

System.out.print(nums2[i] + " ");

System.out.println();
Riccardo Flask 106 |
Page
JAVA for Beginners

// now operate on nums1 array through nums2

nums2[3] = 99;

System.out.print("Here is nums1 after change through


nums2: ");

for(i=0; i < 10; i++)

System.out.print(nums1[i] + " ");

System.out.println();

Predicted Output:

Here is nums1: 0 1 2 3 4 5 6 7 8 9

Here is nums2: 0 -1 -2 -3 -4 -5 -6 -7 -8 -9

Here is nums2 after assignment: 0 1 2 3 4 5 6 7 8 9

Here is nums1 after change through nums2: 0 1 2 99 4 5 6 7 8 9

The Length Variable:

This variable automatically keeps track of the number of items an array can hold and NOT the actual
items. When an array is declared to have ten items, even if one does not put actual data, the length
of the array is 10. Something to keep in mind is also when dealing with two dimensional arrays. As
already explained in the theory lessons, two dimensional arrays are considered to be an array of
arrays. Hence calling up the length of such array would return the number of sub-arrays. To access
the length of the particular sub-array, one has to write the ‘row’ index, e.g. arrayname [0].length

// length of array demo

class LengthDemo {

public static void main(String args[]) {

int list[] = new int[10];

int nums[] = { 1, 2, 3 };
Riccardo Flask 107 |
Page
JAVA for Beginners

int table[][] = { // a variable-length table


0 1 2 3
{1, 2, 3},
0 1 2 3
{4, 5}, 1 4 5
2 6 7 8 9
{6, 7, 8, 9}

};

System.out.println("length of list is " +


list.length);

System.out.println("length of nums is " +


nums.length);

System.out.println("length of table is " +


table.length); // returns number of rows

System.out.println("length of table[0] is " +


table[0].length);

System.out.println("length of table[1] is " +


table[1].length);

System.out.println("length of table[2] is " +


table[2].length);

System.out.println();

// using length to initialize list

for(int i=0; i < list.length; i++)

list[i] = i * i;

System.out.print("Here is list: ");

// using length to display list

for(int i=0; i < list.length; i++)

System.out.print(list[i] + " ");

System.out.println();

Predicted Output:

Riccardo Flask 108 |


Page

You might also like