Variables Arrays and Strings

Variable Type Bytes of Storage Range
boolean 2 True, False
byte 1 -128 to 127
char 2 N/A
double 8 -1.7976931348623E308 to -9406545841247E-324 for negative values.
4 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
float 4 -3.4028223E38 to -1.401298E-45 for negative values and 1.401298E-45 to 3.402823E38 for positive values.
int 4 -2147483648 to 2147483647
long 8 -9223372036854775808 to 9223372036854775807
short 2 -32768 to 32767




Integer variable

Example of Integer variable,

public class app
{
public static void main(String[] args)
{
int days;
days=365;
System.out.println("Number of days = "+days);
}
}

Ex. Long can have more digits than int values, so java provides an explicit way of creating long.

public class app
{
public static void main(String[] args)
{
long value;
value=1234567890123456789L;
System.out.println("The value = "+value);
}
}

Ex. You can also create literals in octal format by starting them with a leading zero and in hexadecimal format by starting them with 0x or 0X.

public class app
{
public static void main(String[] args)
{
int value;
value=16;
System.out.println("16 decimal = "+value );
value=020;
System.out.println("20 octal = "+value+" in decimal" );
value=0x10;
System.out.println("10 hexadecimal = "+value+" in decimal");
}
}

Output:

C:\> java app
16 decimal =16
20 octal =16 in decimal
10 hexadecimal =16 in decimal

Java uses four types of integers, each with its own number of bytes put aside for it in memory: byte (one byte), short (two bytes), int (four bytes) and long (eight bytes).

Ex.

public class app
{
public static void main(String[] args)
{
byte byte1;
short short1;
int int1;
long long1;

byte1=1;
short1=100;
int1=10000;
long1=100000000;

System.out.println("Byte1 = "+byte1 );
System.out.println("Short1 = "+short1 );
System.out.println("int1 = "+int1 );
System.out.println("Long1 = "+Long1 );
}
}

Output:

Byte1 = 1
Short1 = 100
Int1 = 10000
Long1= 100000000

Ex. Initial variable.

public class app
{
public static void main(String[] args)
{
int int1, int2=200;
int1=100;
System.out.println("The Int1 = "+ int1 +"\nThe Int2 = "+ int2);
}
}

Output:

The Int1 = 100
The Int2 = 200

Ex. Dynamic initialize:

public class app
{
public static void main(String[] args)
{
int int1=2, int2=3;
System.out.println("The Int1 = "+ int1 +"\tThe Int2 = "+ int2);
int int3=int1*int2;
int1=int3;
System.out.println("\nThe Int1 = "+ int1 +"\tThe Int3 = "+ int3);
}
}

Output:

The Int1 = 2 The Int2 = 3
The Int1 = 6 The Int3 = 6

Converting between data type:

Automatic conversation:

When you're assigning one type of data to a variable of another type, java will convert the data to the new variable type automatically if both the following conditions are true:

1. The data type and the variable types are compatible.
2. The target type has a larger range than the source type.

Ex.

public class app
{
public static void main(String[] args)
{
byte byte1=1;
int int1;
int1=byte1;
System.out.println("The Int1 = "+ int1);
}
}

Output:

The Int1 = 1

Casting to new data type:

If you want to perform a narrowing conversion, you must use an explicit cast which looks like this,

(target-data-type) value

Ex.

public class app
{
public static void main(String[] args)
{
byte byte1;
int int1=1;
byte1=(byte) int1;
System.out.println("The Byte1 = "+ byte1);
}
}

=> Without the explicit type cast, the compiler would object, but with the type cast, there's no problem, because java decides that you know about the possibility of losing some data when you cram a possible larger value into a smaller type. For example, when you put a floating-point number into a long, the fractional part of the number will be truncated, and you may lose more data if the floating-point value is outside the range that a long can hold.

Ex.

public class vari {
public static void main(String[] args) {
char char1='A';
int int1;
int1=(int) char1;
System.out.println(" Character converted to Integer = "+ int1);
}
}

However, because java knows that multiplying bytes can result in integer-sized values, it automatically promotes the result of the byte1*byte2 operation into an integer, which means we actually have to use an explicit cast here to get back to the byte type.

Ex.

public class app_dynamic1
{
public static void main(String[] args)
{
byte byte1=100,byte2=100;
byte byte3;
byte3= byte1*byte2/100;
System.out.println("\nThe Byte3 = "+ byte3);
}
}

Output:

C:\>javac app_dynamic1.java
app_dynamic1.java:7: possible loss of precision found : int required: byte
byte3= byte1*byte2/100;
^
1 error

=> For this reason, we have to add an explicit cast to get back to the byte type. Example is given in below.

public class app_dynamic1
{
public static void main(String[] args)
{
byte byte1=100,byte2=100;
byte byte3;
byte3=(byte) (byte1*byte2/100);
System.out.println("\nThe Byte3 = "+ byte3);
}
}

Outout:

C:\>javac app_dynamic1.java

The Byte3 = 100


Float Variable

Floating-point literals are of type double by default in java code, example include 3.1415926535, 1.5 and 0.1111111. We can also indicate a power of 10 with e or E, such as 1.345E10. This is the same as 1.345*1010 or -9.999E-23, which is the same as -9.999*10-23.

Ex.

public class app
{
public static void main(String[] args)
{
float value;
value=1.5;
System.out.println("The value = "+value);
}
}

Output:

C:\> javac app.java

appt.java:6: possible loss of precision found : double required: float
value=1.5;
^
1 erro

=> Unfortunately, the default type for floating-point literals is double, so java gives me the following error. we can fix this by explicitly making my literal into a float,

public class app
{
public static void main(String[] args)
{
float value;
value=1.5f;
System.out.println("The value = "+value);
}
}

Output:

C:\> javac app.java

The value = 1.5

Java has two built-in types of floating-point variables, each with its own number of bytes set aside for it in memory: float (four bytes) and double (eight bytes).

Ex.

public class app
{
public static void main(String[] args)
{
float float1;
double double1;

float1=1.11111111111F;
double1=1.1111111111111E+9D;

System.out.println("Float1 = "+float1 );
System.out.println("Double1 = "+double11 );
}
}

Output:

C:\>java app

float1 = 1.1111112
double1 = 1.1111111111111E9


Boolean Variable

Boolean values can only be true or false in java.

Ex.

public class app
{
public static void main(String[] args)
{
boolean value1;
value1=true;
System.out.println("The value = "+value);
}
}

Output:

c:\> java app

the value = true

Ex. Here, we are using these two boolean variables with the java if statement. We test the value in boolean1 with the if statement, making the code display the message "boolean1 is true."

public class app
{
public static void main(String[] args)
{
boolean boolean1, boolean2;
boolean1=true;
boolean2=false;
System.out.println("The Boolean1 = "+boolean1);
System.out.println("The Boolean2 = "+boolean2);
if( boolean1 ){
System.out.println("The Boolean1 is TRUE");
} else {
System.out.println("The Boolean1 is FALSE");
}
}
}

Output:

C:\> java app

The Boolean1 = true
The Boolean2 = false
The Boolean1 is TRUE



Character Variable

Character literals are actually numbers that act as indexes into the Unicode character set, not actual characters.

Ex. The Unicode code for the letter C is 67. Therefore, the following application prints out a C:

public class app
{
public static void main(String[] args)
{
char char_value;
char_value=67;
System.out.println("The Character = "+char_value);
}
}

Output:

C:\> java app

The Character = C

Ex. You can also refer to the Unicode code for the letter C with a character literal, which you would enclose in single quotes.

public class app
{
public static void main(String[] args)
{
char char_value;
char_value='C';
System.out.println("The Character = "+ char_value);
System.out.println("The Character + 1 = "+ char_value + 1);
System.out.println("++char_value = "+ ++char_value);
}
}

Output:

C:\> java app

The Character = C
The Character + 1 = C1
++char_value = D

Note: You can also enclose special character escape sequences in single quotes to make character literals that you couldn't make by typing a single character. Here are the escape sequences.

\' - Single quote
\" - Double quote
\\ - Back slash
\b - Back Space
\ddd - Octal character
\f - Form feed
\n - New line; called a line feed in DOS and Windows.
\r - Carriage return
\uxxxx- Hexadecimal Unicode character.

Ex.

public class app
{
public static void main(String[] args)
{
System.out.println(" He said, \"Hello\" ");
}
}

Output:

C:\> java app

He said, "Hello"



Array

Declaring one-dimensional Array:

Arrays provide an easy way of handling a set of data by index. Getting an array ready for use is a two-step process. First, you must declare the array. The next step is to actually create that array by allocating memory for it.

Ex.

public class app
{
public static void main(String[] args)
{
double accounts[]; // First Step
accounts=new double[100]; // Second Step
...........
...........
}
}

Note: The lower bound of all java arrays is 0, so the first element in the array is accounts[0] and the last element is accounts[99]. That means total element is 100. If the array index is outside the range o to 99, java will create a fatal error and the program will halt.

In fact, we can combine the declaration and creation process into one step for arrays.

Ex.

public class app
{
public static void main(String[] args)
{
double accounts[]=new double[100]; // Declared in one statement
...........
...........
}
}

To initialize the data in one-dimensional array, you just place the values between curly braces, one value after the other, separated by commas, beginning with the first value in the array.

Ex.

public class app
{
public static void main(String[] args)
{
double accounts[]={238.45, 999.33, 0, 1335.67, 1111.11};
accounts[2]=99999.99;
System.out.println("Accounts[0] = "+ accounts[0] +"\nAccounts[2] = "+ accounts[2] +"\nAccounts[4] = "+ accounts[4]);
}
}

Output:

Accounts[0] = 238.45
Accounts[2] = 99999.99
Accounts[4] = 1111.11

Declaring Multidimensional Arrays:

You can declare multidimensional arrays in much the same way you declare one-dimensional arrays; just include a pair of square brackets for every dimension in the array.

Syntax: type array_name[][][]....;

Ex.

public class app
{
public static void main(String[] args)
{
double accounts[][]=new double[2][100]; // Two dimensional array
double account_id[][][][]=new double[2][3][4][5]; // Four dimensional array
...........
...........
}
}

Ex. Creating multidimensional Arrays.

public class app
{
public static void main(String[] args)
{
double accounts[][];
accounts = new double[2][100];
accounts[0][3] = 345.98
accounts[1][3] = 23456.65
System.out.println("Saving Account 3 has $ "+ accounts[0][3]);
System.out.println("Checking Account 3 has $ "+ accounts[1][3]);
}
}

Output:

Saving Account 3 has $ 345.98
Checking Account 3 has $ 23456.65

Ex. Initializing Multidimensional arrays.

public class app
{

public static void main(String[] args)
{
double accounts[][] = {{10.11,19.56,
12.56,48.78} , {11.20,34.74,25.58,45.67}};
System.out.println("Saving Account 3 has $ "+ accounts[0][2]);
System.out.println("Checking Account 3 has $ "+ accounts[1][2]);
}
}

Output:

Saving Account 3 has $ 12.56
Checking Account 3 has $ 25.58

Ex. We can construct arrays as we like as in this example, in which each row of a two-dimensional array has a different number of elements. which is called Creating Irregular Multidimensional Array.

public class app
{
public static void main(String[] args)
{
double accounts[][] = new double[5][];
accounts[0] = new double[500];
accounts[1] = new double[400];
accounts[2] = new double[300];
accounts[3] = new double[200];
accounts[4] = new double[100];

array[3][3] = 2666.76
System.out.println("Account[3][3] has $ "+ accounts[3][3]);
}
}

Output:

Account[3][3] has $ 2666.76

Ex. Getting an array's length. Such as how many elements are in that array.

public class app
{

public static void main(String[] args)
{
double grades[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
System.out.println("The length of Array = "+ grades.length);
}
}

Output:

The length of Array = 10



String

String objects hold text strings that you can't change; if you want to change the actual text in the string, you should use the StringBuffer class instead.

Creating Strings:

Ex..

public class app
{
public static void main( String[] args)
{
String s1="Hello from JAVA!";

String s2;
s2="Hello from JAVA!"

String s3= new String();
s3="Hello from JAVA!";

String s3= new String("Hello from JAVA!");

char c1[]={'H','i',' ','f','r','o','m',' ','J','A','V','A','!'};
String s5=new String(c1);

String s6=new String(c1,0,2);

double d1=1.23456789;
String s7=String.valueOf(d1);

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7);
}
}

Output:

Hello from JAVA!
Hello from JAVA!
Hello from JAVA!
Hello from JAVA!
Hi
1.23456789

Topñ

Getting length of String:

Ex.

public class app
{
public static void main(String[] args)
{
String s1="Hello from JAVA!";
System.out.println("\""+ s1 +"\" is "+ s1.length() +" Characters long.");
System.out.println("\"Hello\" is "+ "Hello".length() +" Characters long.");
}
}

Output:

"Hello from JAVA!" is 16 Characters long.
"Hello" is 5 Characters long.

Topñ

Concatenating String:

Ex. Concatenating String is used to join two strings and create a new one.

public class app
{
public static void main(String[] args)
{
String s1="Hello ";

String s2=s1 + "from ";
String s3=s2 + "Java!";

String s4=s1.concat("from ");
String s5=s4.concat("Java!");

System.out.println(s3);
System.out.println(s5);
}
}

Output:

Hello from JAVA!
Hello from JAVA!

Topñ

Getting Characters and Substrings:

Ex. Getting characters is used to get the character at a specific position. You can also use the substring method to create a new string that's substring of the old one, like this:

public class app
{
public static void main(String[] args)
{
String s1="Hello from JAVA!";

char c1=s1.charAt(0);
System.out.println("The first character of \" "+ s1 + " \" is "+ c1);

char chars1[]=s1.toCharArray(); // Getting a Character from given String
System.out.println("The second character of \" "+ s1 + " \" is "+ chars1[1]);

char chars2[]=new char[5]; // Getting characters from given String
s1.getChars(0,5,chars2,0);
System.out.println("The first five characters of \" "+ s1 + " \" are "+ new String(chars2));

String s2=s1.substring(0,5); // Getting Substrings from given String
System.out.println("The first five characters of \"" + s1 +" \" are "+ s2);
}
}

Output:

C:\jdk1.3\myproject>java app
The first character of "Hello from JAVA!" is H
The second character of "Hello from JAVA!" is e
The first five characters of " Hello from JAVA!" are Hello
The first five characters of "Hello from JAVA!" are Hello

Topñ

Searching for and replacing Strings:

Ex.

public class app
{
public static void main(String[] args)
{
String s1="I have drawn a nice drawing.";

System.out.println("The first occurrence of \"draw\" is "+"at location "+ s1.indexOf("draw")); // Searching from first position

System.out.println("The last occurrence of \"draw\" is "+"at location "+ s1.lastIndexOf("draw")); // Searching from last position

String s2="Edna, you\'re hired!"; // Replacing strings or character
System.out.println(s2.replace('h','f'));
}
}

Output:

C:\jdk1.3\myproject>java app
The first occurrence of "draw" is at location 7
The last occurrence of "draw" is at location 20
Edna, you're fired!

Topñ

Changing Case In Strings:

Ex.

public class app
{
public static void main(String[] args)
{
System.out.println("Hello from Java!".toLowerCase());
System.out.println("Hello from Java!".toUpperCase());
}
}

Output:

hello from java!
HELLO FROM JAVA!

Topñ

Formatting Numbers in Strings:

You can format numbers in strings using the Number-Format class of the java.text package. This class supports the format, set-Minimum-Integer-Digits, Set-Minimum-Fraction-Digits, Set-Maximum-Integer-Digits and Set-Maximum-Fraction-Digits method.

Ex. Using the set-Maximum-Fraction-Digits method, in which I round off a double value as I format it.

import java.text.*;
public class app
{
public static void main(String[] args)
{
double value=1.23456789;
NumberFormat nf=NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(6);
String s=nf.format(value);
System.out.println(s);
}
}

Output:

1.234568

Topñ

Creating StringBuffers:

Ex. here's how to create an empty StringBuffer object and then insert some text into it.

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer();
s1.insert(0,"Hello from Java!");
System.out.println(s1);

StringBuffer s2=new StringBuffer("Hello from Java!");
System.out.println(s2);

StringBuffer s3=new StringBuffer(10);
s3.insert(0,"Hello from Java!");
System.out.println(s3);
}
}

Output:

Hello from Java!
Hello from Java!
Hello from Java!

Topñ

Getting and Setting StringBuffer Lengths and Capacities:

You can use the StringBuffer class's length method to find the lengths of the text in StringBuffer objects and you can use the capacity method to find the amount of memory space allocated for that text. You can also set the length of the text in a StringBuffer object with the setLength method, which lets you truncate strings or extend them with null characters.

Ex.

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Hello from Java!");

System.out.println("The length is "+ s1.length());

System.out.println("The allocated length is "+ s1.capacity());

s1.setLength(2000);

System.out.println("The new length is "+ s1.length());
}
}

Output:

The length is 16
The allocated length is 32
The new length is 2000

Topñ

Setting Character in StringBuffers:

You can set individual characters in strings using the setCharAt.

Ex.

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("She had a wild look in her eyes.");
s1.setCharAt(10,'m');
System.out.println(s1);
}
}

Output:

She had a mild look in her eyes.

Topñ

Appending and Inserting using StringBuffer:

You can use the append method to append strings to the text in a StringBuffer object and you can ue insert method to insert text at a particular location.

Ex. In that example starts with the text "Hello", appends "Java!" and then inserts "from" into the middle of the text using append and insert.

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Hello");
s1.append(" Java!");
System.out.println(s1);
s1.insert(6,"from ");
System.out.println(s1);
}
}

Output:

Hello Java!
Hello from Java!

Topñ

Deleting Text in StringBuffer:

You can delete text in a StringBuffer object using the delete and deleteCharAt methods.

Ex.

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("I'm not having a good time.");
s1.delete(4,8);
System.out.println(s1);
}
}

Output:

I'm having a good time.

Topñ

Replacing Text in StringBuffers:

Ex. we're using the StringBuffer class's replace method to change the contents of a StringBuffer object from "Hello from Java!" to "Hello to Java!".

public class app
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Hello from Java!");
s1.replace(6,10,"to");
System.out.println(s1);
}
}

Output:

Hello from Java!

Topñ

String class constructor summary:

Constructor Means
String() Initialize a new String object so that holds an empty character sequence.
String( byte[] bytes)
String( byte[] ascii, int hibyte)
String()
String()
String()
String()
String()
String()