Java Chapter 3 - Variables

3.1 Variable Types

The ranges of integer variable is shown below.

byte    (1 byte)   -128 to 127
short   (2 bytes)  -32,768 to 32.767
int     (4 bytes)  -2.1 billion to 2.1 billion
long    (8 bytes)  -9 quintillion to 9 quintillion

float   (4 bytes)  range depends on number of places past decimal
double  (8 bytes)  range depends on number of places past decimal

boolean (1 byte)   1 or 0 (true or false)
char    (2 bytes)  any ASCII or Unicode character

3.2 Declaring and Using Variables

Below are examples of declaring and using variables.

short Value1 = 5, Value2 = 7, Sum;
sum = Value1 + Value2;

char Percent = '%';
char MyGrade = 'A';

float Money = 5.75;

boolean EndProgram = true;

The following is an example program that uses some of the variable types.

 variables.java // This Java program demonstrates some variable types public class variables {    public static void main (String[] args)    {       double Wage = 12.25, Hours = 5.5, Pay;       char Initial = 'D';       Pay = Wage * Hours;       System.out.println(Initial + " gets paid \$" + Pay);    } } Output D gets paid \$67.375

3.3 Mathematical Operations

The following mathematical operations can be used in Java:

 Code Output Comments System.out.print(5 + 2 * 3); 11 Java follows the order of operations. System.out.print(20 % 7); 6 Modulus gives you the remainder in a division. System.out.print(3 / 2); System.out.print(3.0 / 2.0); 1 1.5 Remember to use decimal points in division. int C = 5; C++; System.out.print(C); 6 ++ is a shortcut way to increment a variable. int C = 5; C--; System.out.print(C); 4 -- is a shortcut way to decrement a variable. int C = 5; C+=5; System.out.print(C); 10 This is the same as C = C + 5 int C = 5; C*=5; System.out.print(C); 25 This is the same as C = C * 5 double A = 2.5; int B = (int)A; System.out.print(B); 2 You may need to cast the variable type.

3.4 String Class

In Java, strings are represented as an instance of a class.  Below is an example of declaring and using a string.

String Name = "Joshua";
System.out.println("My name is " + Name);

There are many methods for the string class.  Some of these are demonstrated in the program below.

 stringdemo.java // This Java program demonstrates some of the string methods public class stringdemo {    public static void main(String[] args)    {       String S1 = "lemon", S2 = "lime", S3 = " CHIPS ";       System.out.println("1. Length of S1 = " + S1.length());       System.out.println("2. Character at position 3 of S1 = " + S1.charAt(3));       System.out.println("3. " + S2.toUpperCase());       System.out.println("4. I like " + S3.trim().toLowerCase() + " and salsa");       System.out.println("5. Location of 'o' in S1 = " + S1.indexOf('o'));       System.out.println("6. Substring Example: " + S3.substring(3,5));       System.out.println("7. Replace Example: " + S1.replace("emo","iste"));    } } Output 1. Length of S1 = 5 2. Character at position 3 of S1 = o 3. LIME 4. I like chips and salsa 5. Location of 'o' in S1 = 3 6. Substring Example: HI 7. Replace Example: listen

Below is a list of the string methods.  Assume the following declaration:

String A = "apple", B = "orange", C = "pear,grape";

 Method Result Description Length A.length() 5 The length of A Comparison A.equals(B) false True if the two strings are equal A.equalsIgnoreCase(B) false Same as above but ignores the case A.compareTo(B) -14 If A < B, returns < 0; If A == B; returns 0; If A > B, returns > 0 A.compareToIgnoreCase(B) -14 Same as above, but ignores the case A.startsWith("ap") true True if A begins with "ap" A.endsWith("x") false True if A ends with "x" Searching A.contains("pp") true True if A contains "pp" A.indexOf("p") 1 Location of first occurrence of "p" A.indexOf("e",3) 4 Location of first occurrence of "e" at or after position 3 A.lastIndexOf("p") 2 Location of last occurrence of "p" A.lastIndexOf("p",1) 1 Location of last occurrence of "p" at or before position 1 Getting Parts B.charAt(3) n Character at position 3 B.substring(1) range Substring from position 1 to end B.substring(1,4) ran Substring from position 1 to before position 4 String[] Parts = C.split(",") Parts="pear" Parts="grape" Splits a string using the specified delimiter (e.g. a comma).  The parts are placed into an array. Changing Strings B.toUpperCase() ORANGE Converts to all uppercase B.toLowerCase() orange Converts to all lowercase B.trim() orange Removes leading and trailing spaces B.replace("an","xx") orxxge Replace all "an" substrings with "xx" String T = "ab:cd:ef"; String[] Parts; Parts = T.split(":"); Parts = "ab" Parts = "cd" Parts = "ef" Splits a string using the specified delimiter into elements of an array

In addition, a number can be converted to a string as shown below,

int Age = 21;
String MyAge = String.valueOf(Age);

3.5 Arrays

To declare and initialize an array in one line, you can do the following:

double[] HourlyWage = {7.25, 10.75, 12.0, 8.55, 9.5};

To access individual elements in the array:

HourlyWage += 1.0;              // Makes first element 8.25
HourlyWage = HourlyWage;     // Makes second element 9.5

To declare a 10 element array without initializing:

int[] SomeNumber = new int;    // Besides variables, it can be an array of objects

Below is a program that increments each element of an array using a loop.

 array.java public class array {    public static void main (String[] args)    {       double[] HourlyWage = {7.25, 10.75, 12.0, 8.55, 9.5};       for(int x=0; x<=4; x++)       {          HourlyWage[x] += 1;          System.out.println(HourlyWage[x]);       }    } } Output 8.25 11.75 13.0 9.55 10.5