Sie sind auf Seite 1von 52

Data Types, Arrays

Data Types
Java defines eight simple (or elemental) types of data:
byte, short, int, long, char, float, double, and
boolean.
These can be put in four groups:
Integers This group includes byte, short, int, and long,
which are for whole valued signed numbers.
Floating-point numbers This group includes float and
double, which represent numbers with fractional
precision.
Characters This group includes char, which represents
symbols in a character set, like letters and numbers.
Boolean This group includes Boolean, which is a special
type for representing true/false values
Integers
Java defines four integer types: byte, short, int, and long. All of these
are signed, positive and negative values.
long 64, int 32, short 16, byte 8

Byte

The smallest integer type is byte. This is a signed 8-bit type that has a
range from 128 to 127.
Variables of type byte are especially useful when youre working with
a stream of data from a network or file. They are also useful when
youre working with raw binary data that may not be directly
compatible with Javas other built-in types.
short
short is a signed 16-bit type. It has a range from 32,768 to
32,767. It is probably the least-used Java type, since it is defined
as having its high byte first
int
The most commonly used integer type is int. It is a signed 32-bit
type that has a range from 2,147,483,648 to 2,147,483,647. In
addition to other uses, variables of type int are commonly
employed to control loops and to index arrays.
Long

long is a signed 64-bit type and is useful for those occasions
where an int type is not large enough to hold the desired value.
The range of a long is quite large. This makes it useful when big,
whole numbers are needed.
Floating-Point Types
Floating-point numbers, also known as real numbers, are
used when evaluating expressions that require fractional
precision.
float
The type float specifies a single-precision value that uses
32 bits of storage. Single precision is faster on some
processors and takes half as much space as double
precision, but will become imprecise when the values are
either very large or very small
double
Double precision, as denoted by the double keyword,
uses 64 bits to store a value. Double precision is actually
faster than single precision on some modern processors
that have been optimized for high-speed mathematical
calculations. All transcendental math functions, such as
sin( ), cos( ), and sqrt( ), return double values.

Characters
In Java, the data type used to store characters is char.
However, C/C++ programmers beware: char in Java
is not the same as char in C or C++. In C/C++, char
is an integer type that is 8 bits wide. This is not the
case in Java. Instead, Java uses Unicode to represent
characters. Unicode defines a fully international
character set that can represent all of the characters
found in all human languages, in Java char is a 16-bit
type.
Booleans
Java has a simple type, called boolean, for logical
values. It can have only one of two
possible values, true or false.

The Scope and Lifetime of Variables
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Type Conversion and Casting
Javas Automatic Conversions
When one type of data is assigned to another type of variable, an
automatic type conversion will take place if the following two conditions
are met:
The two types are compatible e.g. an int value to a long variable..
The destination type is larger than the source type, e.g. the int type is
always large enough to hold all valid byte values.
Casting Incompatible Types
If you want to assign an int value to a byte variable, This conversion
will not be performed automatically, because a byte is smaller than an
int. This kind of conversion is sometimes called a narrowing
conversion, since you are explicitly making the value narrower so that it
will fit into the target type.
(target-type) value,
If the integers value is larger than the range of a byte, it will be
reduced modulo (the remainder of an integer division by the) bytes
range.
int a;
byte b;
// ...
b = (byte) a;


Example of type conversion
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
} }
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Arrays
Array is a linear homogeneous data structure, it is simply a
collection of similar type elements.
A specific element of an array is accessed by the index.
One-dimensional array declaration is:
Data_Type Variable_name []= new Data_Type[size];
or
Data_Type [] Variable_name = new Data_Type[size];
In general to create an array three steps are to be followed.
(a) Declaration (b) construction ( c) initialization
Declaration conveys array name and the type of its elements
to the java compiler e.g. int [] inta;
Construction means calling the new operator to allocate
memory for the array variable.
During the initialization process, elements of array initialized to
their default values.


Byte 0, int -0, float- o.o f, char-\u0000 , short- 0,
long-oL , double- 0.od, boolean-false , reference-null.

Public class Demo
{
int [] arr = new int [2];
system.out.println(arr[0]);
system.out.println(arr[1]);
}
}
Out put: 0 0

public class Demo
{
public static void main (String[] args)
{
int [] mak = new int[3];
mak[0] =1;
mak[1] =2;
mak[3] =3;
System.out.println(mak[0]);
System.out.println(mak[1]);
System.out.println(mak[2]);
}
}
O/P= 1
2
3
The new operator will allocate memory from heap, mak is a reference type
variable, which mean that it will hold the address of memory location.


mak
6556
stack
Heap
1 2
3
Mak[0] Mak[1] Mak[2]
6556 6560 6564
Representation of array in memory
mak
stack
6556
mak
stack
6556
mak
stack
Explicit Initialization of Arrays
Java provides a declaration form to explicitly specify the initial values of the
elements of an array.
Assuming an n element array, the general form is:
ElementType[] id = {expr
0
, expr
1
, ..., expr
n-1
};
where each expr
i
is an expression that evaluates to type ElementType.

Examples:
int[] fibonacci = {1, 1, 2, 3, 5, 8, 13, 21, 34};
String[] cats = {bug, squeaky, paris, kitty
kat};
int[] unit = {1};


Constant Arrays
As in other declarations, the modifier final can be applied in an array
declaration. The modifier has the usual effect after its initialization, the
array variable is treated as a constant. In this case, the array variable
cannot change which array it references, however, the values in the array
can be changed!
final int[] B = {10, 20};
Graphically this would look like the following:



where indicates that the value of the reference cannot be changed.
B = new int[2]; //illegal: a final cannot be the
//target of an assignment
B[1] = 30; //legal: B[1] is not final
B

10 20
Arrays of Objects
If the element type of an array is an object type, then the elements
hold either the value null or references to element type values rather
than holding element type values themselves. This is illustrated
graphically below:
String[] s = new String[2];
s[0] = Orlando;
s[1] = Florida;
s
Orlando Florida
Array Bounds
Unlike many programming languages, Java automatically checks
that proper array subscripts are used. If a subscript is determined to
be invalid, an exception of type IndexOutOfBoundsException is
generated. (Unless the program provides exception handling code,
this exception causes the program to terminate.)
The following code segment contains two misuses of array sample.
int[] sample = new int[40];
sample[-1] = 0; //subscript too small
sample[40] = 10; //subscript too large


Member Methods and Arrays
Because an array is a Java object, an array as associated with it all
of the member methods of an Object (e.g., clone() and
equals()). However, the array clone() method is overridden
specifically for arrays.
In addition to member methods, an array also has a public final
data field length specifying the number of elements in the array.
Designers of Java were quite helpful to programmer by including this
field as it is a convenience not found in many other programming
languages. This allows the programmer to do the following:
int fibonacci = {1, 1, 2, 3, 5, 7, 13, 21, 34, 55};
for (int i = 0; i < fibonacci.length; ++i){
System.out.println(Fibonacci Number + i +
is: , fibonacci[i]);
}

Cloning an Array
Array method clone() returns a duplicate of the array. The new
array object has the same number of elements as the invoking
array. The values of the clone array are duplicates of the invoking
array.
A clone produced in this manner is known as a shallow copy. The
corresponding elements in the two arrays reference the same
objects. The shallowness can be seen by viewing the
representation of the array variables u and v defined in the
following code segment

Point[] u = {new Point(0,0), new Point(1,1),
new Point(2,2) };
Point[] v = u.clone();
Point[] u = {new Point(0,0), new Point(1,1),
new Point(2,2) };
Point[] v = u.clone();

Cloning an Array

u
Point: (0,0) Point: (1,1) Point: (2,2)
v
u[0] u[1] u[2]
Distinct Element by Element Cloning
If a distinct element-by-element clone, say w, of u is needed, it can
be created in the following manner.

Point[] w = new Point[u.length];
for (int i = 0; i < u.length; ++i) {
w[i] = u[i].clone();
}

Array clones created in this fashion are called deep copies.
The result of executing the code shown above is illustrated on the
next page.

Cloning an Array of a Primitive Type
Using the method clone() on an array with a primitive element type
(not an object type) automatically produces a deep copy.
The code shown below illustrates this concept.

int[] x = {4, 5, 6, 7};
int[] y = x.clone();

These two arrays have the following depiction:

x[0] x[1] x[2] x[3]
y[0] y[1] y[2] y[3]
4 5 6 7
x
4 5 6 7
y
Clone of preemptive data type
public class ArrayClone
{
public static void main( String[] args )
{
int[] primes = { 1, 2, 3, 5, 7, 11, 13, 17 };
int[] backup;
backup = primes.clone();
backup[0] = 0;
System.out.println( "Primes: " );
for( int i=0 ; i < primes.length ; i++ )
System.out.print( " " + primes[i] );
System.out.println( "\nbackup: With first Element Modified" );
for( int j=0 ; j < backup.length ; j++ )
System.out.print(" " + backup[j] );
System.out.println();
}
}
Difference b/w copy and clone
class copy
{
public static void main(String [] args)
/*{
int [] numbers = { 2, 3, 4, 5};
int [] numbersCopy = numbers; // in case of copy array;
numbersCopy[2] = 0;
System.out.println(numbers[2]);
System.out.println(numbersCopy[2]);
}
}*/
{

int [] numbers = { 2, 3, 4, 5};
int [] numbersClone = (int[])numbers.clone(); //in case of clone array;
numbersClone[2] = 0;
System.out.println(numbers[2]);
System.out.println(numbersClone[2]);
}
}
Passing Arrays to Methods
Arrays are passed as reference parameters to methods.
Since arrays are passed as reference parameters their
cell values can be modified in the method.
Arrays are mutable in methods.
AddArrays.java
class AddArrays
{
public static void main (String [] args)
{
int[] array1 = {1, 3, 5, 7, 9};
int[] array2 = {2, 4, 6, 8};
System.out.println (Array 1 sum: + sum (array1);
System.out.println (Array 2 sum: + sum (array2);
}
public static int sum (int[] x)
{ int sum = 0;
for (int i = 0; i < length.x; i++)
sum = sum + x [i];
return sum;
}
}
Copying an array
An array is an object and like as any object its name actually the
name of the reference to that object. Assigning an array to another
does not duplicate the array. It merely assigns another reference to
the same object.

System.arraycopy( src, srcpos, dest, destpos, length)
arraycopy( a, 4, b, 2, 3);
would copy 3 elements from a[] to b[].
here elements { a[4], a[5], a[6] } get copied to { b[2], b[3], b[4] }
CopyArrays

class CopyArrays
{
public static void main (String [] args)
{
int[] Array1 = {1, 2, 3, 4};
int[] Array2 = {5, 6, 7, 8};
copy (Array1, Array2);
for (int i=0; i< Array1.length; i++)
System.out.println(Array1[i] + " ");
System.out.flush();
for (int i=0; i< Array2.length; i++)
System.out.print (Array2[i] + " ");
System.out.flush();
}
public static void copy (int[] x, int[] y)
{
for (int i=0; i<x.length;i++)
y[i]=x[i];
}
}

Multi-Dimensional Array
Multi-dimensional arrays are actually arrays of array. It is like a
pointer to an array of pointers.
Two-Dimensional Array
Syntax:
datatype [][] variable=new type[n][m];
int [][] town= new int [3][3];




Town
1000
Stack
1000
Heap
6556
6556
Town[0]
96656
13665
Town[2]
Town[1]
Town[0][0] Town[0][1] Town[0][2]
96656
13665
1000
Representation of multidimensional array in memory
Two dimensional array
class demo
{
public static void main(String args[])
{
int [] [] town= new intb[4] [];
system.out.println(town[0]);
system.out.println(town[1]);
system.out.println(town[2]);
} }

Output:
Null
Null
Null

two-dimensional array
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented
as an array of arrays of int.
// Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
} }
}
This program generates the following output:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
Unequal second dimension array
class demo{
Public static void main( String args[])
{
int [] []town= new int[3] [];
town[0] = new int [1];
town[1] = new int [2];
town[2] = new int [3];
int i, j, k=0;
for (i=0;i<3;i++)
for (j=0;j<3;j++)
{
town [i] [j]= k;
k++;
}
For (i=0;i<3;i++)
{
For (j=0;j<3;j++)
{
system.out.println ( town [i] [j] + );
}
System.out.println();
} } }
Output:
0
1 2
3 4 5

Three-dimensional array
class threeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println(); }
System.out.println();
} } }
This program generates the following output:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12

0 0 0 0 0
0 2 4 6 8
0 4 8 12 16
0 6 12 18 24
Arrays
Advantages
Very efficient, quick to access and add to
Type-safe, can only add items that match the
declared type of the array
Disadvantages
Fixed size, some overhead in copying/resizing
Cant tell how many items in the array, just how large
it was declared to be
Limited functionality, need more general functionality

Strings
A string is a sequence of characters.
Java provides two classes to support strings:
String class the instances of String class are
constants, i.e., the content of a String object
cannot be changed after its creation.
StringBuffer class the instances of StringBuffer
class are mutable, i.e., the content of a
StringBuffer object can be changed after its
creation.
The String class has some unique privileges not
shared by ordinary classes.
A string can be created using string literals.
Operator + can be applicable to strings.
The characters in a string are indexed by 0 to n-1,
where n is the length of the string.
Strings
Each quoted string is an object of the string class and
it is created inside the heap.
Strings are object of predefined class.
Strings in java do not have null character at the end.
String is predefined class present in java.lang
package.
It is final class that means string class can not be
inherited.

String Class
Creation of a String object.
String s = new String(abc);
String s = abc;

Add operator:
String s1 = abc;
String s2 = de;
String s3 = s1 + s2; //s3 = abcde

The String class has a lot of methods. These
methods are useful to manipulate strings.

length and charAt methods
int length() this instance method returns
the length of the string.
String s=abc;
s.length() returns 3

char charAt(int index) this instance
method returns the character at a specific
index.
String s=abcde;
s.length(); 5
s.charAt(0); a
s.charAt(1); b
s.charAt(4); e
s.charAt(5); error
indexOf method
int indexOf(char c)
int indexOf(char c, int index)
Returns the index of the first occurrence of
the character c in the current object starting at
position index (default 0). Returns 1 if there
is no such occurrence. [overloaded method]
String s=ababc;
s.indexOf(b); //returns 1
s.indexOf(b,2); //returns 3
s.indexOf(d,2); //returns -1

indexOf method (cont.)
int indexOf(String s2)
int indexOf(String s2, int index)
Returns the index of the first occurrence of
the substring s2 in the current object,
beginning at position index (default 0).
Returns 1 if there is no such occurrence.
String s=daabcabc;
String s2=ab;
s.indexOf(s2); //returns 2
s.indexOf(s2,3); //returns 5
s.indexOf(s2,6); //returns -1

substring method
String substring(int startindex)
String substring(int startindex, int lastindex)
Returns the substring of the current object
starting from startindex and ending with
lastindex-1 (or the last index of the string if
lastindex is not given). [overloaded method]
String s=abcdef;
s.substring(1); //returns bcdef
s.substring(3); //returns def
s.substring(1,4);//returns bcd
s.substring(3,5);//returns de


equals and equalsIgnoreCase
boolean equals(String s2)
boolean equalsIgnoreCase(String s2)
Returns true if the current object is equal to
s2; otherwise false.
The method equalsIgnorecase disregards
the case of the characters.

String s=abc;
s.equals(abc) //returns true
s.equals(abcd) //returns false
s.equals(aBc) //returns false
s.equalsIgnoreCase(aBc)//returns true
String program
class String01{
String str1 = "THIS STRING IS NAMED str1";
String str2 = "This string is named str2";

public static void main(String[] args){
String01 obj = new String01();
System.out.println("Display original string values");
System.out.println(obj.str1);
System.out.println(obj.str2);
System.out.println("Replace str1 with another string");
obj.str1 = obj.str1 + " " + obj.str2;
System.out.println("Display new string named str1");
System.out.println(obj.str1);
System.out.println("Terminating program");
}//end main()
}
StringBuffer Class
StringBuffer constructors:
StringBuffer()
StringBuffer(int size)
Returns an instance of the StringBuffer class that
is empty but has an initial capacity of size
characters (default 16 characters).

StringBuffer(String arg)
Creates an instance of the StringBuffer class
from the string arg.

length and charAt methods are also
defined for StringBuffer class.
StringBuffer length vs. capacity
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
output:
buffer = Hello
length = 5
capacity = 21
Reading strings using BufferedReader
Recall from our earlier look at using
BufferedReader that we need to first declare
a BufferedReader object that was directed to
read from the input stream attached to the
standard input device. Once this is done,
reading strings from the keyboard is
straightforward.

BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));

BufferedReader Example
import java.io.*;

public class readName {
public static void main(String[] args)throws IOException{

BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter your first name: ");
String firstName = stdin.readLine();
System.out.println("Enter your last name: ");
String lastName = stdin.readLine();
System.out.println("Your name is " + firstName + " "+ lastName + ".");
}
}
Wordlength Example
import java.io.*;

public class Wordlength {
public static void main(String[] args) throws IOException {
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));

//read the word from the user
System.out.println(Enter a word: );
String word = stdin.readLine();

//determine the length of the word
int wordLength = word.length();

//output results
System.out.println(Word + word + has a length of
+ wordLength + characters.);
}
}



Palindrome Example
//Checks words to see if they are palindromes
import java.io.*;

public class Palindrome {
static boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
boolean flag = true;
while ((i<j) && flag){
if (s.charAt(i) != s.charAt(j))
flag = false;
else {i++; j--; }
}
return flag;
}


Palindrome Example (cont.)
public static void main(String args[]) throws IOException {
String s;
BufferedReader stdin = new BufferedReader (new InputStreamReader
(System.in));

System.out.print("A String > ");
System.out.flush();
s = stdin.readLine();

if (isPalindrome(s))
System.out.println(s + " is a palindrome");
else
System.out.println(s + " is not a palindrome");
}
}

Decimal to Binary -- Example
import java.io.*;
public class DecToBinary {
static StringBuffer toBinary(int decVal) {
StringBuffer sb = new StringBuffer("");
if (decVal == 0)
sb.insert(0,"0"); //note insert position
else
while (decVal != 0) {
if (decVal%2 == 0)
sb.insert(0,"0"); //note insert position
else
sb.insert(0,"1"); //note insert position
decVal = decVal / 2;
}
return sb;
}

Decimal to Binary Example (cont.)
public static void main(String args[]) throws IOException {
int num;
BufferedReader stdin =
new BufferedReader (new InputStreamReader(System.in));

System.out.print("An integer > ");
System.out.flush();
num = Integer.parseInt(stdin.readLine().trim());

System.out.println("Decimal Number: " + num +
" Corresponding Binary Number: " + toBinary(num));
}
}

Das könnte Ihnen auch gefallen