Mobile Development Workshop Introduction to Java
Overview Computer hardware, software, and programming languages The Java programming language Simple Java statements Data, variables, and types Classes, objects, and methods Control flow Conditional statements Loops Graphical User Interfaces
Hardware and Software Computer systems consist of hardware and software. Hardware includes the tangible parts of computer systems. Software includes programs - sets of instructions for the computer to follow. Familiarity with hardware basics helps us understand software.
Memory Memory holds Two kinds of memory programs data for the computer to process the results of intermediate processing. Two kinds of memory main memory auxiliary memory
Bits, Bytes, and Addresses A bit is a digit with a value of either 0 or 1. A byte consists of 8 bits. Each byte in main memory resides at a numbered location called its address.
Main Memory Figure 1.1
Programs A program is a set of instructions for a computer to follow. We use programs almost daily (email, word processors, video games, bank ATMs, etc.). Following the instructions is called running or executing the program.
Running a Program
Programming Languages High-level languages are relatively easy to use Java, C#, C++, Visual Basic, Python, Ruby. Unfortunately, computer hardware does not understand high-level languages. Therefore, a high-level language program must be translated into a low-level language.
Compilers A compiler translates a program from a high-level language to a low- level language the computer can run. You compile a program by running the compiler on the high-level- language version of the program called the source program. Compilers produce machine- or assembly-language programs called object programs.
Java Byte-Code The Java compiler does not translate a Java program into assembly language or machine language for a particular computer. Instead, it translates a Java program into byte-code. Byte-code is the machine language for a hypothetical computer (or interpreter) called the Java Virtual Machine.
Compiling and Running a Program
Writing our first Java Programs Write a program that operates like this: Sample screen output
Printing to the screen System.out is an object for sending output to the screen. println is a method to print whatever is in parentheses to the screen. System.out.println (“Whatever you want to print”);
Printing to the screen The object performs an action when you invoke or call one of its methods objectName.methodName(argumentsTheMethodNeeds);
Object-Oriented Programming Our world consists of objects (people, trees, cars, cities, airline reservations, etc.). Objects can perform actions which affect themselves and other objects in the world. Object-oriented programming (OOP) treats a program as a collection of objects that interact by means of actions.
OOP Terminology Objects, appropriately, are called objects. Actions are called methods. Objects of the same kind have the same type and belong to the same class. Objects within a class have a common set of methods and the same kinds of data but each object can have it’s own data values.
OOP Design Principles OOP adheres to three primary design principles: Encapsulation Polymorphism Inheritance
Introduction to Encapsulation The data and methods associated with any particular class are encapsulated (“put together in a capsule”), but only part of the contents is made accessible. Encapsulation provides a means of using the class, but it omits the details of how the class works. Encapsulation often is called information hiding.
Example An automobile consists of several parts and pieces and is capable of doing many useful things. Awareness of the accelerator pedal, the brake pedal, and the steering wheel is important to the driver. Awareness of the fuel injectors, the automatic braking control system, and the power steering pump is not important to the driver.
Introduction to Inheritance Classes can be organized using inheritance. A class at lower levels inherits all the characteristics of classes above it in the hierarchy. At each level, classifications become more specialized by adding other characteristics. Higher classes are more inclusive; lower classes are less inclusive.
Introduction to Inheritance
Variables Variables store data such as numbers and letters. Think of them as places to store data. They are implemented as memory locations. The data stored by a variable is called its value. The value is stored in the memory location. Its value can be changed.
Naming and Declaring Variables Choose names that are helpful such as count or speed, but not c or s. When you declare a variable, you provide its name and type. int heightInCentimeters,age; A variable's type determines what kinds of values it can hold (int, double, char, etc.). A variable must be declared before it is used.
Data Types A class type is used for a class of objects and has both data and methods. "Java is fun" is a value of class type String A primitive type is used for simple, nondecomposable values such as an individual number or individual character. int, double, and char are primitive types.
Primitive Types
Primitive Types Four integer types (byte, short, int, and long) int is most common Two floating-point types (float and double) double is more common One character type (char) One boolean type (boolean)
Examples of Primitive Values Integer types 0 -1 365 12000 Floating-point types 0.99 -22.8 3.14159 5.0 Character type 'a' 'A' '#' ' ' Boolean type true false
Assignment Statements An assignment statement is used to assign a value to a variable. answer = 42; The "equal sign" is called the assignment operator. We say, "The variable named answer is assigned a value of 42," or more simply, "answer is assigned 42."
Assignment Examples amount = 3.99; firstInitial = 'W'; birthYear = currentYear - age; total = total + 2;
Assignment Compatibilities Java is said to be strongly typed. You can't, for example, assign a floating point value to a variable declared to store an integer. Sometimes conversions between numbers are possible. doubleVariable = 7; is possible even if doubleVariable is of type double, for example.
Arithmetic Operators Arithmetic expressions can be formed using the +, -, *, and / operators together with variables or numbers referred to as operands. When both operands are of the same type, the result is of that type. When one of the operands is a floating-point type and the other is an integer, the result is a floating point type.
Arithmetic Operators Example If hoursWorked is an int to which the value 40 has been assigned, and payRate is a double to which 8.25 has been assigned hoursWorked * payRate is a double with a value of 500.0.
The Division Operator The division operator (/) behaves as expected if one of the operands is a floating-point type. When both operands are integer types, the result is truncated, not rounded. Hence, 99/100 has a value of 0.
The mod Operator The mod (%) operator is used with operators of integer type to obtain the remainder after integer division. 14 divided by 4 is 3 with a remainder of 2. Hence, 14 % 4 is equal to 2. The mod operator has many uses, including determining if an integer is odd or even determining if one integer is evenly divisible by another integer.
Sample Expressions
The Class String We've used constants of type String already. "Enter a whole number from 1 to 99." A value of type String is a Sequence of characters Treated as a single item.
Concatenation of Strings Two strings are concatenated using the + operator. String greeting = "Hello"; String sentence; sentence = greeting + " madam"; System.out.println(sentence); Any number of strings can be concatenated using the + operator.
Class and Method Definitions
Class and Method Definitions Objects that are instantiations of the class Automobile
Methods When you use a method you "invoke" or "call" it Two kinds of Java methods Return a single item Perform some other action – a void method The method main is a void method Invoked by the system Not by the application program
Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement chooses between two or more possible actions. A loop statement repeats an action until a stopping condition occurs.
The if-else Statement A branching statement that chooses between two possible actions. Syntax if (Boolean_Expression) Statement_1 else Statement_2
Semantics of the if-else Statement
Omitting the else Part
Introduction to Boolean Expressions The value of a boolean expression is either true or false. Examples time < limit balance <= 0
Java Comparison Operators
Compound Boolean Expressions Boolean expressions can be combined using the "and" (&&) operator. Example if ((score > 0) && (score <= 100)) ... Not allowed if (0 < score <= 100)
Java Logical Operators
Multibranch if-else Statements
Multibranch if-else Statements if (score >= 90) grade = 'A'; else if ((score >= 80) && (score < 90)) grade = 'B'; else if ((score >= 70) && (score < 80)) grade = 'C'; else if ((score >= 60) && (score < 70)) grade = 'D'; else grade = 'F';
Loops A portion of a program that repeats a statement or a group of statements is called a loop. The statement or group of statements to be repeated is called the body of the loop. A loop could be used to compute grades for each student in a class. There must be a means of exiting the loop.
The while Statement Also called a while loop A while statement repeats while a controlling boolean expression remains true The loop body typically contains an action that ultimately causes the controlling boolean expression to become false.
The while Statement Syntax while (Boolean_Expression) Body_Statement or { First_Statement Second_Statement … }
The while Statement
The do-while statement Also called a do-while loop Similar to a while statement, except that the loop body is executed at least once Syntax do Body_Statement while (Boolean_Expression); Don’t forget the semicolon!
Slot Machine Algorithm Ask the user to play the game or quit If the user decides to play Generate 3 random numbers If all 3 numbers match, display the message “Jackpot” If any two numbers match, display the message “Matched 2” Otherwise, display the message “Sorry. Better luck next time” Repeat until the user quits
The for Statement A for statement executes the body of a loop a fixed number of times. Example for (count = 1; count <= 10; count++) System.out.println(count);
The for Statement Syntax Corresponding while statement for (Initialization, Condition, Update) Body_Statement Body_Statement can be either a simple statement or a compound statement in {}. Corresponding while statement Initialization while (Condition) Body_Statement_Including_Update
The for Statement
Graphical User Interfaces Graphical User Interfaces (GUIs) give users a visual representation of a program’s interface The help communicate how a user can navigate the app as well as ways to perform common actions It’s important that developers conform to a visual language with which users are familiar Reduces cognitive load Creates more intuitive user experience Makes programmers’ lives easier
Event-driven programming GUI applications usually involve event driven programming This is when aspects or your program may not be executed until some event occurs Even-driven programs are generally more complex because we have more things to consider (things like event order and variable scope)
Building GUI applications in Java Java has many facilities for building GUIs Many based on the Java Foundation Classes Swing is a very common toolkit used today to build user interfaces
The basics Start with a JFrame object This is your main window It will contain other components that comprise your user interface By default jframe objects are invisible You’ll want to change that property once you’ve build your interface Be default jframe objects are compact You can specify a fixed size, or have the frame adjust automatically to snugly wrap its children
Events and event handling Events can be triggered in a program by user action on the interface When an event occurs, it will have a specific target component Some components display default behavior (usually visual) when it receives an event You can override or augment this behavior by implementing an event handler
Implementing event listeners Some events can target any component, and can therefore have those events handled https://docs.oracle.com/javase/tutorial/uiswing/events/eventsandcomponents.html#all Some events only target certain components https://docs.oracle.com/javase/tutorial/uiswing/events/eventsandcomponents.html#many
Common Swing components Common button types http://docs.oracle.com/javase/tutorial/uiswing/components/button.html#checkbox Common text field types https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html Other Swing components https://docs.oracle.com/javase/tutorial/uiswing/components/componentlist.html
Swing layouts Containers (such as a JFrame or JPanel) must be told how to lay out their children This is accomplished by using a layout Containers have default layouts, but you may want to change them
Swing layouts https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
Simple Slot Machine 2.0 Extend original slot machine utilizing GUI components