What is Switch Statement in java
What is Switch Statement in java
A switch statement
is useful when you need to select one of several alternatives based on the
value of an integer, a character, or a String variable.
The basic form of the switchstatement is this:
switch (expression)
{
case constant:
statements;
break;
[ case constant-2:
statements;
break; ] ...
[ default:
statements;
break; ] ...
}
Example:
package com.opps;public class SwitchExample {
public static void main(String[] args) {
int lan = 3;
String language;
switch (lan) {
case 1:
language = "C";
break;
case 2:
language = "C++";
break;
case 3:
language = "JAVA";
break;
case 4:
language = "VC++";
break;
case 5:
language = ".NET";
break;
default:
language = "Invalid language";
break;
}
System.out.println(language);
}
}
output:
JAVA
What is Arrays in java
An array is
a collection of variables of the same type. For instance, an array of int is
a collection of variables of the type int. The variables in the array are
ordered and each have an index. You will see how to index into an array later
in this text. Here is an illustration of Java arrays:
Declaring an Array
Variable in Java
A Java array variable
is declared just like you would declare a variable of the desired type, except
you add[] after the type. Here is a simple Java array declaration example:
int[] intArray;
You can use a Java
array as a field, static field, a local variable, or parameter, just like any
other variable. An array is simply a variation of the data type. Instead of
being a single variable of that type, it is a collection of variables of that
type.
Here are a few more
Java array declaration examples:
String[] stringArray;
MyClass[] myClassArray;
The first line declares
an array of String references. The second line declares an array of
references to objects of the class MyClass, which symbolizes a class you
have created yourself.
You actually have a
choice about where to place the square brackets [] when you declare an array in
Java. The first location you have already seen. That is behind the name of the
data type (e.g. String[]). The second location is after the variable name.
The following Java array declarations are actually all valid:
int[] intArray;
int intArray[];
String[] stringArray;
String stringArray[];
MyClass[] myClassArray;
MyClass myClassArray[];
Personally I prefer to
locate the square brackets [] after the data type (e.g. String[]) and not
after the variable name. After all, an array is a special kind of data type, so
I feel it is easier to read the code when the square brackets are placed right
after the data type in the array declaration.
When you declare a Java
array variable you only declare the variable (reference) to the array itself.
The declaration does not actually create an array. You create an array like
this:
int[] intArray;
intArray = new int[10];
This example creates an
array of type int with space for 10 int variables inside.
Once an array has been
created its size cannot be changed. In some languages arrays can change their
size after creation, but in Java an array cannot change its size once it is
created. If you need an array-like data structure that can change its size, you
should use a List.
The previous Java array
example created an array of int which is a primitive data type. You
can also create an array of object references. For instance:
String[] stringArray =
new String[10];
Java allows you to
create an array of references to any type of object (to instances of any
class).
The Java programming
language contains a shortcut for instantiating arrays of primitive types and
strings. If you already know what values to insert into the array, you can use
an array literal. Here is how how an array literal looks in Java code:
int[] ints2 = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
Notice how the values
to be inserted into the array are listed inside the { ... } block.
The length of this list also determines the length of the created array.
Actually, you don't
have to write the new int[] part in the latest versions of Java. You
can just write:
int[] ints2 = { 1,2,3,4,5,6,7,8,9,10 };
It is the part inside
the curly brackets that is called an array literal.
This style works for
arrays of all primitive types, as well as arrays of strings. Here is a string
array example:
String[] strings = {"one",
"two", "three"};
Each variable in an
Java array is also called an "element". Thus, the example shown
earlier created an array with space for 10 elements, and each element is a
variable of type int.
Each element in the
array has an index (a number). You can access each element in the array via its
index. Here is an example:
intArray[0] = 0;
int firstInt =
intArray[0];
This example first sets
the value of the element (int) with index 0, and second it reads the value of
the element with index 0 into an int variable.
You can use the
elements in a Java array just like if they were ordinary variables. You can
read their value, assign values to them, use the elements in calculations and
pass specific elements as parameters to method calls.
The indexes of elements
in a Java array always start with 0 and continue to the number 1 below the size
of the array. Thus, in the example above with an array with 10 elements the
indexes go from 0 to 9.
You can access the
length of an array via its length field. Here is an example:
int[] intArray = new
int[10];
int arrayLength = intArray.length;
In this example the
variable named arrayLength will contain the value 10 after the second
line of code has been executed.
You can loop through
all the elements of an array using the.java for loop Here is an example of
iterating an array with a for loop in Java:
String[] stringArray =
new String[10];
for(int i=0; i <
stringArray.length; i++) {
stringArray[i] = "String no " +
i;
}
for(int i=0; i <
stringArray.length; i++) {
System.out.println( stringArray[i] );
}
This example first
creates an array of String references. When you first create an array
of object references, each of the cells in the array points to null -
no object.
The first of the two for loops
iterate through the String array, creates a String and
makes the cell reference that String.
The second of the two for loops
iterate through the String array and prints out all of the strings
that the cells reference.
If this had been an
array of int (primitive values), it could have looked like this:
int[] intArray = new
int[10];
for(int i=0; i <
intArray.length; i++) {
intArray[i] = i;
}
for(int i=0; i <
intArray.length; i++) {
System.out.println( intArray[i] );
}
The variable i is
initialized to 0 and runs up until the length of the array minus 1. In this
case, i takes the values 0 through 9, each time repeating the code
inside the for loop one time, and for each iteration i has
a different value.
You can also iterate an
array using the "for-each" loop in Java. Here is how that looks:
int[] intArray = new
int[10];
for(int theInt :
intArray) {
System.out.println(theInt);
}
The for-each loop gives
you access to each element in the array, one at a time, but gives you no
information about the index of each element. Additionally, you only have access
to the value. You cannot change the value of the element at that position. If
you need that, use a normal for-loop as shown earlier.
For for-each loop also
works with arrays of objects. Here is an example showing you how to iterate an
array of String objects:
String[] stringArray =
{"one", "two", "three"};
for(String theString :
stringArray) {
System.out.println(theString);
}
The examples shown
above all created arrays with a single dimension, meaning elements with indexes
going from 0 and up. It is, however, possible to create arrays where each
element has two or more indexes which identify (locate) it in the array.
You create a
multidimensional array in Java by appending one set of square brackets ([]) per
dimension you want to add. Here is an example that creates a two-dimensional
array:
int[][] intArray = new
int[10][20];
This example creates a
two-dimensional array of int elements. The array contains 10 elements
in the first dimension, and 20 elements in the second dimension. In other
words, this examples creates an array of arrays of int elements. The
array of arrays has space for 10 int arrays, and each int array
has space for 20 int elements.
You access the elements
in a multidimensional array with one index per dimension. In the example above
you would have to use two indexes. Here is an example:
int[][] intArray = new
int[10][20];
intArray[0][2] = 129;
int oneInt = intArray[0][2];
The variable named oneInt will
contain the value 129 after the last line of Java code has executed.
When you iterate a
multidimensional array in Java you need to iterate each dimension of the array
separately. Here is is how iterating a multidimensional looks in Java:
int[][] intArray = new
int[10][20];
for(int i=0; i <
intArrays.length; i++){
for(int j=0; j < intArrays[i].length;
j++){
System.out.println("i: " + i
+ ", j: " + j);
}
}
Sometimes you need to
insert elements into a Java array somewhere. Here is how you insert a new value
into an array in Java:
int[] ints = new int[20];
int insertIndex = 10;
int newValue = 123;
//move elements below insertion
point.
for(int
i=ints.length-1; i > insertIndex; i--){
ints[i] = ints[i-1];
}
//insert new value
ints[insertIndex] =
newValue;
System.out.println(Arrays.toString(ints));
The example first
creates an array. Then it defines an insert index and a new value to insert.
Then all elements from the insertion index and to the end of the array are
shifted one index down in the array. Note that this will shift the last value
in the array out of the array (it will simply be deleted).
The above array insertion
code could be embedded in a Java method. Here is how that could look:
public void
insertIntoArray(
int[] array, int insertIndex, int
newValue){
//move elements below insertion point.
for(int i=array.length-1; i >
insertIndex; i--){
array[i] = array[i-1];
}
//insert new value
array[insertIndex] = newValue;
}
This method takes an int[] array
as parameter as well as the index to insert the new value, and the new value.
You can insert elements into an array by calling this method like this:
int[] ints = new int[20];
insertIntoArray(ints,
0, 10);
insertIntoArray(ints,
1, 23);
insertIntoArray(ints,
9, 67);
Of course, if the insertIntoArray() method
is located in a different class than the above code, you would need an object
of that class in order to be able to call the method. Or, if the insertIntoArray() method
was static, you would need to put the class name and a dot in front of the
method name.
Sometimes you have want
to remove an element from a Java array. Here is the code for removing an
element from an array in Java:
int[] ints = new int[20];
ints[10] = 123;
int removeIndex = 10;
for(int i =
removeIndex; i < ints.length -1; i++){
ints[i] = ints[i + 1];
}
This example first
creates an int array. Then it sets the value of the element with
index 10 to 123. Then the example removes the element with index 10. It removes
the element by shifting all elements below index 10 one position up in the
array. After the removal, the last element in the array will exist twice. Both
in the last and second last element.
The above code could be
embedded in a Java method. Here is how such an array removal Java method could
look:
public void removeFromArray(
int[] array, int removeIndex){
for(int i = removeIndex; i <
array.length -1; i++){
array[i] = array[i + 1];
}
}
This removeFromArray() method
takes two parameters: The array to remove the element from, and the index of
the element to remove.
Of course, if the removeFromArray() method
is located in a different class than the above code, you would need an object
of that class in order to be able to call the method. Or, if the removeFromArray() method
was static, you would need to put the class name and a dot in front of the
method name.
Sometimes you may need
to find the minimum or maximum value in a Java array. Java does not have any
built-in functions for finding minimum and maximum value, so I will show you
how to code that yourself.
Here is first how you
find the minimum value in an array:
int[] ints =
{0,2,4,6,8,10};
int minVal =
Integer.MAX_VALUE;
for(int i=0; i <
ints.length; i++){
if(ints[i] < minVal){
minVal = ints[i];
}
}
System.out.println("minVal
= " + minVal);
The example first sets
the minVal to Integer.MAX_VALUE which is the highest
possible value an int can take. This is done to make sure that the
initial value is not by accident smaller than the smallest value in the array.
Second, the example
iterates through the array and compares each value to minValue. If the
element in the array is smaller than minVal then minVal is
set to the value of the element.
Finally the minimum
value found in the array is printed out. In the example above the minimum value
is 0.
Here is how you find
the maximum value in an array. It is pretty similar to finding the minimum
value.
int[] ints =
{0,2,4,6,8,10};
int maxVal =
Integer.MIN_VALUE;
for(int i=0; i <
ints.length; i++){
if(ints[i] > maxVal){
maxVal = ints[i];
}
}
System.out.println("maxVal
= " + maxVal);
This example will print
out the value 10.
The major differences
to finding the minimum value is the initialization of maxVal and the
comparison ofmaxVal to the elements in the array.
Java contains a special
utility class that makes it easier for you to perform many often used array
operations like copying and sorting arrays, filling in data, searching in
arrays etc. The utility class is calledArrays and is located in the
standard Java package java.util. Thus, the fully qualified name of the
class is:
java.util.Arrays
I will cover a few of
the methods found in this class in the following sections. Remember, in order
to usejava.util.Arrays in your Java classes you must import it. Here is
how importing java.util.Arrays could look in a Java class of your
own:
package myjavaapp;
import
java.util.Arrays;
public class MyClass{
public static void main(String[] args) {
}
}
Notice the import
java.util.Arrays; statement in bold. It is this statement that imports the
classjava.util.Arrays into your Java class.
You can copy an array
into another array in Java in several ways.
The first way to copy
an array in Java is to iterate through the array and copy each value of the
source array into the destination array. Here is how copying an array looks
using that method:
int[] source = new
int[10];
int[] dest = new int[10];
for(int i=0; i <
source.length; i++) {
source[i] = i;
}
for(int i=0; i <
source.length; i++) {
dest[i] = source[i];
}
First two int arrays
are created. Second, the source array is initialized with values from 0 to 9 (0
to the length of the array minus 1). Third, each element in the source array is
copied into the destination array.
The second method to
copy a Java array is to use the Arrays.copyOf() method. Here is how
copying an array using Arrays.copyOf() looks:
int[] source = new
int[10];
for(int i=0; i <
source.length; i++) {
source[i] = i;
}
int[] dest =
Arrays.copyOf(source, source.length);
The Arrays.copyOf() method
takes 2 parameters. The first parameter is the array to copy. The second
parameter is the length of the new array. This parameter can be used to specify
how many elements from the source array to copy.
The third method to
copy a Java array is to use the Arrays.copyOfRange() method. TheArrays.copyOfRange() method
copies a range of an array, not necessarily the full array. Here is how copying
a full array using Arrays.copyOfRange() in Java looks:
int[] source = new
int[10];
for(int i=0; i <
source.length; i++) {
source[i] = i;
}
int[] dest =
Arrays.copyOfRange(source, 0, source.length);
The Arrays.copyOfRange() method
takes 3 parameters. The first parameter is the array to copy. The second
parameter is the first index in the source array to include in the copy. The
third parameter is the last index in the source array to include in the copy
(excluded - so passing 10 will copy until and including index 9).
You can convert an Java
array of primitive types to a String using the Arrays.toString() method.
Here is an example of how to convert an array of int to a String using Arrays.toString():
int[] ints = new int[10];
for(int i=0; i <
ints.length; i++){
ints[i] = 10 - i;
}
System.out.println(java.util.Arrays.toString(ints));
The first line creates
an array of int with 10 elements. The for loop initializes
the array with the values from 10 to 1. The last line prints out the value
returned from Arrays.toString(). The returned String(which is
printed) looks like this:
[10, 9, 8, 7, 6, 5, 4,
3, 2, 1]
You can sort the
elements of an array using the Arrays.sort() method. Sorting the
elements of an array rearranges the order of the elements according to their
sort order. Here is an Arrays.sort() example:
int[] ints = new int[10];
for(int i=0; i <
ints.length; i++){
ints[i] = 10 - i;
}
System.out.println(java.util.Arrays.toString(ints));
java.util.Arrays.sort(ints);
System.out.println(java.util.Arrays.toString(ints));
The first line declares
and instantiates an array of int with a length of 10;
The for loop
iterates over the array and inserts values into each element. The values
inserted will go from 10 to 1 in descending order.
After the for loop
the array is converted to a String using Arrays.toString() and
printed out to the console (command line). At this point the output written to
the console (the String version of the array) looks like this:
[10, 9, 8, 7, 6, 5, 4,
3, 2, 1]
The array is then
sorted using Arrays.sort(). The elements will now be ordered in ascending
order.
After sorting the
array, it is again converted into a String and printed to the
console. The output printed this time looks like this:
[1, 2, 3, 4, 5, 6, 7,
8, 9, 10]
The Arrays.sort() example
shown earlier only works for Java arrays of primitive data types. Java's
primitive data types have a natural ordering, either their numeric order, or
the order of the characters in the ASCII table (the binary number representing
the character).
If you want to sort an
array of objects you need to use a different method. Objects may not have any
natural sort order, so you need to provide another object which is capable of
determining the order of your objects. Such an object is called a Comparator.
What are the DataTypes in java
DataTypes in java
As explained in the
text about java variable , each variable in Java has a data type. Data
types into two groups:
Primitive data types
Object references
A variable takes up a
certain amount of space in memory. How much memory a variable takes depends on
its data type.
A variable of a
primitive data type contains the value of the variable directly in the memory
allocated to the variable. For instance, a number or a character.
A variable of an object
reference type is different from a variable of a primitive type. A variable of
an object type is also called a reference.
The variable itself does not contain the object, but contains a reference to the object. The
reference points to somewhere else in memory where the whole object is stored.
Via the reference stored in the variable you can access fields and methods of
the referenced object. It is possible to have many different variables
reference the same object. This is not possible with primitive data types.
The Java language
contains the following primitive data types:
|
Data type
|
Description
|
|
boolean
|
A binary value of
either true or false
|
|
byte
|
8 bit signed value,
values from -128 to 127
|
|
short
|
16 bit signed value,
values from -32.768 to 32.767
|
|
char
|
16 bit Unicode
character
|
|
int
|
32 bit signed value,
values from -2.147.483.648 to 2.147.483.647
|
|
long
|
64 bit signed value,
values from -9.223.372.036.854.775.808 to 9.223.372.036.854.775.808
|
|
float
|
32 bit floating point
value
|
|
double
|
64 bit floating point
value
|
That these are
primitive data types means that they are not objects, nor references to objects
(classes and objects are explained in later texts in this Java tutorial).
Here is an example of
how you declare a variable of a primitive type:
int myInt;
The primitive types
also come in versions that are full-blown objects. That means that you
reference them via an object reference that you can have multiple references to
the same value, and you can call methods on them like on any other object in Java.
The list of core object data types below contains the object versions of the
primitive types. The list also contains a few others of the core object types
in Java.
|
Data type
|
Description
|
|
Boolean
|
A binary value of
either true or false
|
|
Byte
|
8 bit signed value,
values from -128 to 127
|
|
Short
|
16 bit signed value,
values from -32.768 to 32.767
|
|
Character
|
16 bit Unicode
character
|
|
Integer
|
32 bit signed value,
values from -2.147.483.648 to 2.147.483.647
|
|
Long
|
64 bit signed value,
values from -9.223.372.036.854.775.808 to 9.223.372.036.854.775.808
|
|
Float
|
32 bit floating point
value
|
|
Double
|
64 bit floating point
value
|
|
String
|
N byte Unicode string
of textual data. Immutable
|
Notice how object types
are spelled with a capital letter in the beginning of their name, where the
primitive version (non-object) is spelled in all lowercase characters. There
are also abbreviation differences, likeint vs. Integer and char vs. Character.
There are of course
many other components you can use in the Java API, but the above mentioned data
types are the core Java types. The String type is explained in more detail in
its own text: java Strings
You can also create your own more complex data
types by creating custom classes. I will get back to how in a later text.
Here is how you declare
a variable of (reference to) one of the core object types:
Integer myInteger;
When you declare an
object reference variable, the reference does not point to any object. You need
to create (instantiate) an object first. Here is how that is done:
Integer myInteger;
myInteger = new
Integer(45);
This example makes the myInteger variable
reference an Integer object which internally contains the value 45.
It is the new Integer(45) part of the code that creates the Integer object.
You can also create the
object already when the variable is declared, like this:
Integer myInteger = new Integer(45);
The object versions of
the primitive data types are immutable, meaning the values stored inside them
cannot be changed once set. For instance, the value stored inside an Integer object
cannot be changed once the object has been created.
The variable that
references the object can be made to point to another object though. Here is an
example:
Integer myInteger = new
Integer(45);
myInteger = new
Integer(33);
As you can see, the
variable in the example is made to point to another Integer object.
Before Java 5 you had
to call methods on the object versions of the primitive types, to get their
value out as a primitive type. For instance:
Integer myInteger = new
Integer(45);
int myInt = myInteger.intValue();
From Java 5 you have a
concept called "auto boxing". That means that Java can automatically
"box" a primitive variable in an object version, if that is required,
or "unbox" an object version of the primitive data type if required.
For instance, the example before could be written like this:
Integer myInteger = new
Integer(45);
int myInt = myInteger;
In this case Java would
automatically extract the int value from the myInteger object
and assign that value to myInt.
Similarly, creating an
object version of a primitive data type variable was a manual action before
Java:
int myInt = 45;
Integer myInteger = new
Integer(myInt);
With auto boxing Java
can do this for you. Now you can write:
int myInt = 45;
Integer myInteger =
myInt;
Java will then
automatically "box" the primitive data type inside an object version
of the corresponding type.
Java's auto boxing
features enables you to use primitive data types where the object version of
that data type was normally required, and vice versa. There is one pitfall to
keep in mind though. A variable of type object (a reference to an object) can
point to null, meaning it points to nothing - no object. If you try to
convert null to a primitive value you will get a NullPointerException (an
error that causes the program to fail). This code shows an example of that:
Integer myInteger =
null;
int myInt = myInteger;
This code will compile
alright, but when executed it will result in NullPointerException because
the variable myInteger points to null. It is thus not possible
to convert (unbox) the value of the object it points to, because it does not
point to any object.













