ANDROID FUNDAMENTAL WORKSHOP Java Basic structure of an

ANDROID FUNDAMENTAL WORKSHOP Java

Basic structure of an application A Java application consists of a definition of a class. The name of the class (Class. Name) and the name of the file (Class. Name. java) must be identical. The class definition has a header (public class Class. Name) followed by a body inside braces. The body of the class may contain a method called “main”. The main method always has the modifiers public, static and void in front of it.

Demo: Hello. World Write the following program on your computer public class Hello. World { public static void main (String[] args) { System. out. println("Hello World!"); } }

Primitive data types and operations There are eight java primitives boolean true or false byte signed 8 -bit integer char 16 -bit Unicode 2. 0 character short signed 16 -bit integer int signed 32 -bit integer long signed 64 -bit integer float signed 32 -bit floating-point double signed 64 -bit floating-point

Primitive data types and operations Most often you will use…. booleans for true/false variables true, false chars for characters a, b, c … ints for integers 1, 2, 3 … (not 1. 00) doubles for decimals 1. 0, 3. 14, 9. 9999999 …

Primitive data types and operations Java is a strongly typed language. An explicit type must be assigned to every data value. Ex: int x = 5; int y; y = 7; int z = x + y; System. out. println(z); Output: 12 Notice that x, y and z are all declared as ints You can only declare a variable once!!! int x = 5; int x = 6; Can’t re-declare x!!

Primitive data types and operations Common operations on primitives Addition, Multiplication, etc Modulus double z = x + y, double z = x * y int z = x % y Numerical comparison and equality boolean z = ( x < y ) boolean a = (x = = y) Recall that one equals sign ( = ) is an assignment Two equals signs ( = = ) is a comparison

Primitive data types and operations Casting Will this compile? double x = 3; double y = 2; int z = x / y; Notice that a double has 64 bits, while an int has only 32. Trying to assign the value of x/y to z is like trying to pour a gallon of water into a 2 -liter bottle. Try this instead…. double x = 3; double y = 2; int z = (double)(x / y); This is called casting. But be careful! You could lose precision. In the above example z will equal 1, not 1. 5

Primitive data types and operations What is the value of z? Why? int x = 3; int y = 2; int z = x / y; In “integer math” the decimal gets thrown out. z equals 1, not 1. 5

Primitive data types and operations Modulus is a useful operation. It results in the remainder of the division operation. 10 %3=1 6%2=0 5%3=2 14 % 5 = 4 What is the value of z? int z = 8 % 3;

Using predefined objects One of the strengths of Java is the ability to create objects in your program from a large variety of predefined classes. Notice that primitive data types create a variable, whereas a class produces an object. Each pre-defined class has a collection of public methods defined for it.

Using predefined objects The String class One of the first classes you used in Java was the String class. A String represents a sequence of characters. To create a String object: String s = new String(“A string of characters”); There is also a short-hand way to create a String: String s = “Another string of characters”;

Using predefined objects Methods of the String class int length(): returns the number of characters in a String s = "this is a String"; int i = s. length(); char. At(int index): returns the character at the index specified String s = "this is a String"; char c = s. char. At(3); int index. Of(char target): returns the index of the first occurrence of the target. -1 otherwise. String s = "this is a String"; int i = s. index. Of('S');

Using predefined objects String substring(int start, int end): returns a String that represents the characters from positions “start” to “end” String s = "this is a String"; String t = s. substring(5, 10); Many more! Concatenation You can concatenate two Strings together with the ‘+’ operator. You can also concatenate a String and a primitive. String s = "this is a String. "; String t = "this is also a String"; String u = s + t;

Using predefined objects The Scanner class allows a program to read input taken from standard input. It can be found in the java. util package so you must put “import java. util. *; ” in the program in order to use it. Declare and initialize a Scanner object: Use the Scanner object to obtain an integer value: Scanner s = new Scanner(System. in); int x = s. next. Int(); Use the Scanner object to obtain a decimal value: double y = s. next. Double();

Using predefined objects The Scanner class cont. In order to use the Scanner class to input a String: 1. Declare and initialize the Scanner object 2. Change the delimiter from whitespace to the line separator 3. Use the Scanner object to input a String Scanner s = new Scanner(System. in); s. use. Delimiter( System. get. Property("line. separator") ); String str = s. next();

Branching structures This is the most basic if-statement if (boolean expression) { //do this block of } If the boolean expression is true, the program will execute the next block of code.

Branching structures Compound if–else statements if (boolean expression) { //do this } else if (boolean expression) { //do something else } else { //do yet something else }

Branching structures A switch statement evaluates the given integer and execute the appropriate block of code. switch (x) { case 1: //this block of code will be executed if x equals 1 { System. out. println("first case"); break; } case 2: //this block of code will be executed if x equals 2 { System. out. println("second case"); break; } default: //this block of code will be executed as a default { System. out. println("third case"); break; }

Loops The purpose of a loops is to repeat a block of code many times. for loop while loop do- while loop

Loops for loop Use a for loop when you know exactly how many times you want to repeat the loop. You may know the particular value, or know a variable that contains the value. The for loop has three crucial parts The initialization of the counter The boolean statement that tests the continuation condition Incrementing the counter For loops are useful when working with arrays (as we will see) EX: print hello 5 times. for(int i=0; i<5; i++) { System. out. println("hello"); }

Loops while loop Use a while loop when you want to repeat a block of code an unknown number of times (maybe not at all) A while loop will repeat the block of code until the boolean statement is no longer true while (boolean expression) { //do this block of code }

Loops do-while Use a do-while loop when you want to repeat a block of code an unknown number of times, but at least once. Perfect for user inputs. EX: ask a user for a number between 1 and 10, repeat until the user enters a valid number. Scanner s = new Scanner(System. in); int input; do { System. out. print("Enter a number between 1 and 10: "); input = s. next. Int(); }while(input < 1 || input > 10);

Arrays In Java, arrays are objects You can create an array of any primitive or object class by using “[]” The declaration of an integer array: The declaration of a String array: int[] x; String[] s; Declaring an array does not create the object or allocate memory. It merely creates the variable.

Arrays Initializing arrays: Use the key word “new” to initialize an array and provide the type of the array, and the size of the array within the brackets. int[] x = new int[100]; Creates an int array x, 100 elements long String[] s = new String[10]; Creates a String array s, 10 elements long
![Arrays Modifying elements int[] x = new int[10]; x[0] = 5; x[2] = 8; Arrays Modifying elements int[] x = new int[10]; x[0] = 5; x[2] = 8;](http://slidetodoc.com/presentation_image_h2/44c4df1d8f86e4b138bb5eee34263e6e/image-26.jpg)
Arrays Modifying elements int[] x = new int[10]; x[0] = 5; x[2] = 8; Accessing elements In the above example, a new array is declared and initialized. The 0 th element is set to 5, while the 2 nd element is set to 8. Recall that a 10 element array is numbered 0 through 9. int i = x[2]; In the above example, the program will access the 2 nd element of the array and assign its value to the integer variable i. Array Length In Java, an array knows how long it is. int[] x = new int[20]; int l = x. length;

More on the structure of an application So far the example programs have had only one method (the main method) and none of the examples have had any class variables. In practice, most programs will have many class variables and many methods.

More on the structure of an application Class variables A class variable is declared at the class level, rather than inside the body of a method. Consequently, the scope of variable extends throughout the entire class. public class Test { static int i; public static void main (String[] args) { i = 5; } } Notice that even while the variable i is declared outside the main method, it can still be accessed inside the main method. Also notice the variable i has the modifier “static. ” More on this later.

More on the structure of an application Scope public class Scope { int x = 5; public static void main (String[] args) { int y = 6; if (y == 6) { int z = 7; } } } What is the scope of the variables x, y and z? Notice how proper indentation makes determining the scope easier.

More on the structure of an application Methods – A method has two parts Header – Describes the method in general terms, including its name, visibility, inputs and outputs. Visibility modifier Return type Method Name List of parameters Body – Describes the specific actions the method will perform The body consists of a sequence of program statements to be executed. If the method returns a value, there must be a return statement.

More on the structure of an application Visibility modifiers public Visible outside the class Called a service method private Not visible outside the class It can only be used by methods inside the class Called a support method

More on the structure of an application Return type Can be any primitive, a class, or void. It tells us what kind of result comes back from the method when it is evaluated. If a method is supposed to return a value, there must be a return statement.

More on the structure of an application Method Name Gives the method a name, so that it can be called from elsewhere in the program. The convention is to use lower case letters except for the first letter of subsequent words. No white spaces. EX: calculate. Sum EX: get. Last. Name EX: Set. Phone. Number not convention

More on the structure of an application List of parameters A list of the type and name of the expected inputs Type gives what kind of data is expected for that input Name gives the name by which it will be referred to during the method’s execution Parameters are given in parentheses, separated by commas. There does not need to be any parameters at all if the method does not require them.

More on the structure of an application An example of a method public static int square. Number(int n) { int result = n * n; return result; } Visibility modifier - public Return type - int Method Name - square. Number List of parameters – an int named ‘n’

More on the structure of an application Another Example private static void print. Sum(double x, double y) { double result = x + y; System. out. println(result); } Visibility modifier - private Return type - void Method Name - print. Sum List of parameters – a double named ‘x’ and a double named ‘y’

Method Overloading Methods expect the proper input. The compiler will object if the wrong type or number of variables are supplied as arguments. An overloaded method has several different definitions, all with the same method name, but different types and/or number of inputs.

Method Overloading Signature The ordered list of types of parameters in the header of a method is called a signature. As long as they have different signatures, we can define as many methods as we want with the same name. The compiler will choose the correct method based on the method’s signature.

Objects You have already used built-in classes String and Scanner for example You must now learn to write your own. A class should contain two distinct pieces of information Properties: The state of the object Given by the data members or Behaviors: instance variables The capabilities of the object Given by the methods or instance methods

Objects Anatomy of a class public class Class. Name { //instance variables //constructor(s) //methods(s) }

Objects Instance Variables Typically, instance variables are not directly accessible. All your instance variables should be declared private. public – any program can see (and perhaps modify!) this data private – only visible to methods of the class EX: public class Rectangle { private int width; private int height; …. Any object you create from the Rectangle class will have its own width and height.

Objects Constructors are a special type of method. They are often used to initialize the data members of a class when you create objects. They are automatically called upon declaration of an object. They should be declared public They should have exactly the same name of the class Like any other method, they may or may not have parameters

Objects Constructor cont … public Rectangle(int w, int h) { width = w; height = h; } … In this example the constructor takes two parameters, both ints, and assigns their values to the instance variables of the class.

Objects Constructor cont. . To call the constructor and create an object of the Rectangle class: Rectangle Assuming r = new Rectangle(2, 3); our Rectangle class is complete, this will create Rectangle object with a width of 2 and a height of 3.

Objects Instance methods represent the operations that can be performed by objects in the class The methods can also be public or private When deciding which to use, consider whether or not you want the operation available outside the class. Consider the methods on the following slides Notice the getter and setter methods Notice that the calculate. Area method will be called on a specific Rectangle object and will return the area of a that specific Rectangle object.

Objects public void set. Width(int w) { width = w; } public void set. Height(int h) { height = h; } public int get. Width() { return width; }

Objects public int get. Height() { return height; } public int calculate. Area() { int area = width * height; return area; }

Objects Static Notice that neither of the methods or instance variables in the Rectangle class are static. Static variables or methods belong to the class as a whole rather than to a particular object of the class. You do not need to declare an object from a class in order to use static methods Conversely, you must declare an object from a class in order to use non-static methods Non-static variables belong to a specific instance of the class, not the class as a whole.

Thank you!
- Slides: 49