Java is a widely-used, object-oriented programming language known for its simplicity, portability, and reliability. At the core of Java are classes and objects, with classes serving as blueprints for creating objects that encapsulate data and behaviors. The entry point of any Java program is the main method, where execution begins. Java has a variety of data types, including primitive types like int, float, char, and boolean, as well as objects like String. Control flow is managed using conditional statements such as if-else and switch, as well as loops like for, while, and do-while to iterate over data. Arrays allow the storage of multiple values in a single variable, and methods are used to perform specific tasks or operations. Java is built around the principles of object-oriented programming (OOP), which includes encapsulation (hiding internal data), inheritance (deriving new classes from existing ones), polymorphism (using methods in different ways), and abstraction (simplifying complex systems). Exception handling in Java is done using try, catch, and finally blocks, providing a robust mechanism for managing errors. Java also includes packages for organizing code and provides tools for input and output operations, such as the Scanner class for reading user input. Overall, Java's combination of simplicity, powerful features, and cross-platform capabilities makes it a popular choice for building a wide range of applications, from web and mobile apps to enterprise-level systems.
You said:
java basics long paragraph with 3000 characters
ChatGPT said:
ChatGPT
Java is a powerful, high-level, object-oriented programming language widely used for developing various types of applications, ranging from web applications and mobile apps to enterprise systems and large-scale server applications. One of the key features of Java is its platform independence, made possible by the Java Virtual Machine (JVM), which allows Java programs to run on any device that has the JVM installed. The foundational concept in Java programming is the use of classes and objects. A class serves as a blueprint or template for creating objects, which are instances of that class. Each object can have attributes (fields) and behaviors (methods). The main method is the entry point of any Java program, where the program starts its execution. For example, a simple Java program starts by defining a class with a main method that contains the instructions to be executed. Java supports a rich set of data types including primitive types such as int, float, char, boolean, and double, along with more complex types like String, arrays, and user-defined objects. These data types are essential for storing and manipulating data throughout the program.
Control flow in Java is managed using conditional statements and loops. The if-else statement is commonly used for making decisions based on conditions, while the switch statement is helpful when dealing with multiple potential conditions base
The document provides an overview of procedure-oriented programming and object-oriented programming paradigms. It then discusses Java programming basics including classes, objects, encapsulation, inheritance, polymorphism, and dynamic binding. The rest of the document discusses Java programming concepts like data types, variables, control flow statements, methods, and classes in more detail with examples. It also covers topics like creating and using objects, passing objects as parameters, and constructors.
The document provides an introduction to the Java programming language. It discusses Java's history and key editions. It also covers basic Java concepts like compiling and running a simple "Hello World" program, primitive data types, variables, operators, conditional statements like if/else, and iterative structures like the for loop. Examples are provided throughout to demonstrate syntax and output.
The document provides an overview of the Java programming language and platform. It discusses the Java language basics including variables, operators, control flow statements, and primitive data types. It also covers object-oriented programming concepts, classes and objects, exceptions, and concurrency. Finally, it outlines the Java platform components including the Java Virtual Machine and Java API.
The document provides an overview of key concepts in the Java programming language including:
1. Java language fundamentals including building blocks like identifiers, literals, variables, and wrapper classes. Different types of literals like integral, floating point, character, string and boolean are described.
2. Control structures in Java including selection statements like if-else and switch statements, and iterative statements like while, do-while and for loops. Jump statements like break, continue and return are also covered.
3. Other concepts discussed include arrays, declaring and initializing array variables, and creating arrays using the new operator in Java.
java in Aartificial intelligent by virat andodariyaviratandodariya
This document provides an overview of artificial intelligence programming using Java. It discusses Java basics like classes, objects, variables and control statements. It also describes graph coloring and uniform cost search algorithms. The document contains sections on Java virtual machine, classes, objects, comments, keywords, variables, control flow statements, source code compilation and more. It aims to teach the fundamentals of AI programming using the Java language.
This document provides an overview of artificial intelligence programming using Java. It discusses Java basics like classes, objects, variables and control statements. It also describes graph coloring and uniform cost search algorithms. The document contains sections on Java virtual machine, classes, objects, comments, keywords, variables, control flow statements, source code compilation and more. It aims to teach the fundamentals of AI programming using the Java language.
Unit I Advanced Java Programming Courseparveen837153
This document provides information about an Advanced Java Programming course taught by Dr. S.SHAIK PARVEEN. It includes details about the course such as prerequisites, objectives, units, and basic Java syntax concepts covered. The document outlines topics like variable declarations, operators, control flow statements, arrays, and object-oriented programming concepts in Java. It aims to teach students advanced Java programming skills like implementing object-oriented principles, working with classes, methods, and threads, as well as creating applets, GUI components, and Java beans.
This document provides an overview of the Java programming language. It discusses Java's history and why it was created. It also outlines some of Java's key fundamentals like variables, data types, operators, and control statements. Additionally, it covers object-oriented programming concepts in Java like classes, objects, inheritance and encapsulation. The document is intended to help readers get started with learning Java.
This document provides an overview of Java programming concepts for a class. It discusses the intended audience, history of Java versions, core design principles, what Java is and isn't, comparing Java to C, compiling and running a first Java program, basic programming constructs like data types, operators, control flow, and arrays. It also covers parsing string input, reading keyboard input at runtime, and where to find Java class documentation online. The overall summary is an introduction to Java programming concepts aimed at students new to the language.
This document provides an overview of the Java programming language. It discusses key Java concepts like object-oriented programming, classes, methods, streams, and input/output. It also covers Java syntax like primitive types, variables, operators, flow control, and arrays. The document explains how Java code is compiled to bytecode and run on the Java Virtual Machine, making it platform independent.
This document provides an overview of the Java programming language. It discusses topics such as how Java code is compiled and run, Java's platform independence, object-oriented features like inheritance and polymorphism, basic syntax like variables and loops, and input/output stream manipulation. The document is intended as a tutorial or introduction to Java for learning purposes.
This document provides an overview and agenda for a Java introduction presentation. It covers topics like the types of programming languages, what Java is and why it was developed, how to set up your environment to write Java programs, the basics of the Java language including variables, types, operators, methods, conditionals, loops, arrays, and object-oriented programming concepts. It also discusses how to write a first simple Java program and solve problems using Java.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It also demonstrates how to compile and run a simple Java application and includes examples of code snippets.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
This document provides an introduction to Java programming. It discusses what Java is, its key characteristics like being object-oriented and portable, and how to get started with Java programming. It also covers Java concepts like classes, methods, variables, data types, operators, and how to compile and run a simple Java application.
This document provides an introduction to learning Java, including:
- An overview of Java as an object-oriented language developed by Sun Microsystems, featuring a virtual machine, portability, and memory management.
- Instructions for compiling and running a simple "Hello World" Java program from the command line.
- Explanations of Java programming basics like classes, methods, variables, operators, and control structures.
The document provides an introduction to the Java programming language. It discusses what computer programs and programming languages are, and how Java programs are compiled into bytecode that can run on any machine with a Java interpreter. It then covers basic Java concepts like variables, primitive data types, operators, and object-oriented programming principles. The document includes examples of writing a simple Java program to output "Hello World" and explanations of core Java topics to help new programmers learn the language.
This document provides an introduction to the Java programming language. It outlines the objectives of learning Java as understanding basic programming concepts, object-oriented principles, Java APIs, and exception handling. It then defines Java as both a programming language and platform, describes Java's syntax and how it is compiled and interpreted, and explains the Java virtual machine and application programming interface that make up the Java platform. It also gives examples of primitive data types, operators, control flow structures, and how to use arrays and strings in Java.
Third Review PPT that consists of the project d etails like abstract.Sowndarya6
CyberShieldX is an AI-driven cybersecurity SaaS web application designed to provide automated security analysis and proactive threat mitigation for business websites. As cyber threats continue to evolve, traditional security tools like OpenVAS and Nessus require manual configurations and lack real-time automation. CyberShieldX addresses these limitations by integrating AI-powered vulnerability assessment, intrusion detection, and security maintenance services. Users can analyze their websites by simply submitting a URL, after which CyberShieldX conducts an in-depth vulnerability scan using advanced security tools such as OpenVAS, Nessus, and Metasploit. The system then generates a detailed report highlighting security risks, potential exploits, and recommended fixes. Premium users receive continuous security monitoring, automatic patching, and expert assistance to fortify their digital infrastructure against emerging threats. Built on a robust cloud infrastructure using AWS, Docker, and Kubernetes, CyberShieldX ensures scalability, high availability, and efficient security enforcement. Its AI-driven approach enhances detection accuracy, minimizes false positives, and provides real-time security insights. This project will cover the system's architecture, implementation, and its advantages over existing security solutions, demonstrating how CyberShieldX revolutionizes cybersecurity by offering businesses a smarter, automated, and proactive defense mechanism against ever-evolving cyber threats.
java in Aartificial intelligent by virat andodariyaviratandodariya
This document provides an overview of artificial intelligence programming using Java. It discusses Java basics like classes, objects, variables and control statements. It also describes graph coloring and uniform cost search algorithms. The document contains sections on Java virtual machine, classes, objects, comments, keywords, variables, control flow statements, source code compilation and more. It aims to teach the fundamentals of AI programming using the Java language.
This document provides an overview of artificial intelligence programming using Java. It discusses Java basics like classes, objects, variables and control statements. It also describes graph coloring and uniform cost search algorithms. The document contains sections on Java virtual machine, classes, objects, comments, keywords, variables, control flow statements, source code compilation and more. It aims to teach the fundamentals of AI programming using the Java language.
Unit I Advanced Java Programming Courseparveen837153
This document provides information about an Advanced Java Programming course taught by Dr. S.SHAIK PARVEEN. It includes details about the course such as prerequisites, objectives, units, and basic Java syntax concepts covered. The document outlines topics like variable declarations, operators, control flow statements, arrays, and object-oriented programming concepts in Java. It aims to teach students advanced Java programming skills like implementing object-oriented principles, working with classes, methods, and threads, as well as creating applets, GUI components, and Java beans.
This document provides an overview of the Java programming language. It discusses Java's history and why it was created. It also outlines some of Java's key fundamentals like variables, data types, operators, and control statements. Additionally, it covers object-oriented programming concepts in Java like classes, objects, inheritance and encapsulation. The document is intended to help readers get started with learning Java.
This document provides an overview of Java programming concepts for a class. It discusses the intended audience, history of Java versions, core design principles, what Java is and isn't, comparing Java to C, compiling and running a first Java program, basic programming constructs like data types, operators, control flow, and arrays. It also covers parsing string input, reading keyboard input at runtime, and where to find Java class documentation online. The overall summary is an introduction to Java programming concepts aimed at students new to the language.
This document provides an overview of the Java programming language. It discusses key Java concepts like object-oriented programming, classes, methods, streams, and input/output. It also covers Java syntax like primitive types, variables, operators, flow control, and arrays. The document explains how Java code is compiled to bytecode and run on the Java Virtual Machine, making it platform independent.
This document provides an overview of the Java programming language. It discusses topics such as how Java code is compiled and run, Java's platform independence, object-oriented features like inheritance and polymorphism, basic syntax like variables and loops, and input/output stream manipulation. The document is intended as a tutorial or introduction to Java for learning purposes.
This document provides an overview and agenda for a Java introduction presentation. It covers topics like the types of programming languages, what Java is and why it was developed, how to set up your environment to write Java programs, the basics of the Java language including variables, types, operators, methods, conditionals, loops, arrays, and object-oriented programming concepts. It also discusses how to write a first simple Java program and solve problems using Java.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It also demonstrates how to compile and run a simple Java application and includes examples of code snippets.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
This document provides an overview of Java programming concepts. It introduces Java, discusses its key characteristics like being object-oriented and portable, and covers basic Java concepts such as variables, data types, operators, and methods. It includes examples of simple Java programs and explains how to compile and run a Java application. The document is intended to teach beginners how to get started with Java programming.
This document provides an introduction to Java programming. It discusses what Java is, its key characteristics like being object-oriented and portable, and how to get started with Java programming. It also covers Java concepts like classes, methods, variables, data types, operators, and how to compile and run a simple Java application.
This document provides an introduction to learning Java, including:
- An overview of Java as an object-oriented language developed by Sun Microsystems, featuring a virtual machine, portability, and memory management.
- Instructions for compiling and running a simple "Hello World" Java program from the command line.
- Explanations of Java programming basics like classes, methods, variables, operators, and control structures.
The document provides an introduction to the Java programming language. It discusses what computer programs and programming languages are, and how Java programs are compiled into bytecode that can run on any machine with a Java interpreter. It then covers basic Java concepts like variables, primitive data types, operators, and object-oriented programming principles. The document includes examples of writing a simple Java program to output "Hello World" and explanations of core Java topics to help new programmers learn the language.
This document provides an introduction to the Java programming language. It outlines the objectives of learning Java as understanding basic programming concepts, object-oriented principles, Java APIs, and exception handling. It then defines Java as both a programming language and platform, describes Java's syntax and how it is compiled and interpreted, and explains the Java virtual machine and application programming interface that make up the Java platform. It also gives examples of primitive data types, operators, control flow structures, and how to use arrays and strings in Java.
Third Review PPT that consists of the project d etails like abstract.Sowndarya6
CyberShieldX is an AI-driven cybersecurity SaaS web application designed to provide automated security analysis and proactive threat mitigation for business websites. As cyber threats continue to evolve, traditional security tools like OpenVAS and Nessus require manual configurations and lack real-time automation. CyberShieldX addresses these limitations by integrating AI-powered vulnerability assessment, intrusion detection, and security maintenance services. Users can analyze their websites by simply submitting a URL, after which CyberShieldX conducts an in-depth vulnerability scan using advanced security tools such as OpenVAS, Nessus, and Metasploit. The system then generates a detailed report highlighting security risks, potential exploits, and recommended fixes. Premium users receive continuous security monitoring, automatic patching, and expert assistance to fortify their digital infrastructure against emerging threats. Built on a robust cloud infrastructure using AWS, Docker, and Kubernetes, CyberShieldX ensures scalability, high availability, and efficient security enforcement. Its AI-driven approach enhances detection accuracy, minimizes false positives, and provides real-time security insights. This project will cover the system's architecture, implementation, and its advantages over existing security solutions, demonstrating how CyberShieldX revolutionizes cybersecurity by offering businesses a smarter, automated, and proactive defense mechanism against ever-evolving cyber threats.
This document provides information about the Fifth edition of the magazine "Sthapatya" published by the Association of Civil Engineers (Practicing) Aurangabad. It includes messages from current and past presidents of ACEP, memories and photos from past ACEP events, information on life time achievement awards given by ACEP, and a technical article on concrete maintenance, repairs and strengthening. The document highlights activities of ACEP and provides a technical educational article for members.
Rearchitecturing a 9-year-old legacy Laravel application.pdfTakumi Amitani
An initiative to re-architect a Laravel legacy application that had been running for 9 years using the following approaches, with the goal of improving the system’s modifiability:
・Event Storming
・Use Case Driven Object Modeling
・Domain Driven Design
・Modular Monolith
・Clean Architecture
This slide was used in PHPxTKY June 2025.
https://phpxtky.connpass.com/event/352685/
David Boutry - Mentors Junior DevelopersDavid Boutry
David Boutry is a Senior Software Engineer in New York with expertise in high-performance data processing and cloud technologies like AWS and Kubernetes. With over eight years in the field, he has led projects that improved system scalability and reduced processing times by 40%. He actively mentors aspiring developers and holds certifications in AWS, Scrum, and Azure.
A substation at an airport is a vital infrastructure component that ensures reliable and efficient power distribution for all airport operations. It acts as a crucial link, converting high-voltage electricity from the main grid to the lower voltages needed for various airport facilities. This essay will explore the functions, components, and importance of a substation at an airport.
Functions of an Airport Substation:
Voltage Conversion:
Substations step down high-voltage electricity to lower levels suitable for airport operations, like terminal buildings, runways, and other facilities.
Power Distribution:
They distribute electricity to various loads, including lighting, air conditioning, navigation systems, and ground support equipment.
Grid Stability:
Substations help maintain the stability of the power grid by controlling voltage levels and managing power flows.
Redundancy and Reliability:
Airports often have redundant substations or interconnected systems to ensure uninterrupted power supply, even in case of a fault.
Switching and Control:
Substations provide switching capabilities to connect or disconnect circuits, enabling maintenance and power management.
Protection:
Substations incorporate protective devices, like circuit breakers and relays, to safeguard the power system from faults and ensure safe operation.
Key Components of an Airport Substation:
Transformers: These convert high-voltage electricity to lower voltage levels.
Circuit Breakers: These devices switch circuits on or off, protecting the system from faults.
Busbars: These are large, conductive bars that distribute electricity from transformers to other equipment.
Switchgear: This includes equipment that controls the flow of electricity, such as isolators and switches.
Control and Protection Systems: These systems monitor the substation's performance, detect faults, and automatically initiate corrective actions.
Capacitors: These improve the power factor and reduce losses in the system.
Importance of Airport Substations:
Reliable Power Supply:
Substations are essential for providing reliable power to critical airport functions, ensuring safety and efficiency.
Safe and Efficient Operations:
They contribute to the safe and efficient operation of runways, terminals, and other airport facilities.
Airport Infrastructure:
Substations are an integral part of the airport's infrastructure, enabling various operations and services.
Economic Impact:
Substations support the economic activities of the airport, including passenger and cargo handling.
Modernization and Sustainability:
Modern substations incorporate advanced technologies and systems to improve efficiency, reduce energy consumption, and enhance sustainability.
In conclusion, an airport substation is a crucial component of airport infrastructure, ensuring reliable and efficient power distribution, grid stability, and safe operations.
This presentation highlights project development using software development life cycle (SDLC) with a major focus on incorporating research in the design phase to develop innovative solution. Some case-studies are also highlighted which makes the reader to understand the different phases with practical examples.
11th International Conference on Data Mining (DaMi 2025)kjim477n
Welcome To DAMI 2025
Submit Your Research Articles...!!!
11th International Conference on Data Mining (DaMi 2025)
July 26 ~ 27, 2025, London, United Kingdom
Submission Deadline : June 07, 2025
Paper Submission : https://csit2025.org/submission/index.php
Contact Us : Here's where you can reach us : [email protected] or [email protected]
For more details visit : Webpage : https://csit2025.org/dami/index
This study will provide the audience with an understanding of the capabilities of soft tools such as Artificial Neural Networks (ANN), Support Vector Regression (SVR), Model Trees (MT), and Multi-Gene Genetic Programming (MGGP) as a statistical downscaling tool. Many projects are underway around the world to downscale the data from Global Climate Models (GCM). The majority of the statistical tools have a lengthy downscaling pipeline to follow. To improve its accuracy, the GCM data is re-gridded according to the grid points of the observed data, standardized, and, sometimes, bias-removal is required. The current work suggests that future precipitation can be predicted by using precipitation data from the nearest four grid points as input to soft tools and observed precipitation as output. This research aims to estimate precipitation trends in the near future (2021-2050), using 5 GCMs, for Pune, in the state of Maharashtra, India. The findings indicate that each one of the soft tools can model the precipitation with excellent accuracy as compared to the traditional method of Distribution Based Scaling (DBS). The results show that ANN models appear to give the best results, followed by MT, then MGGP, and finally SVR. This work is one of a kind in that it provides insights into the changing monsoon season in Pune. The anticipated average precipitation levels depict a rise of 300–500% in January, along with increases of 200-300% in February and March, and a 100-150% increase for April and December. In contrast, rainfall appears to be decreasing by 20-30% between June and September.
1. Tutorial: Programming in
Java for Android
Development
Instructor: Adam C. Champion,
Ph.D. CSE 4471: Information
Security Summer 2019
Based on material from C. Horstmann [1], J. Bloch [2], C. Collins et al. [4],
M.L. Sichitiu (NCSU), V. Janjic (Imperial College London), CSE 2221 (OSU), and other
so urces
3. 3
Getting Started (1)
• Need to install Java Dev. Kit (JDK) version 8 to
write Java (Android) programs
– Don’t install Java Runtime Env. (JRE); JDK is different!
– Newer versions of JDK can cause issues with Android
• Can download JDK (free): https://adoptopenjdk.net/
– Oracle’s JDK (http://java.oracle.com) free for dev. only;
payment for commercial use
• Alternatively, for macOS, Linux:
• macOS: Install Homebrew (http://brew.sh), then type
brew cask info adoptopenjdk8 at command line
• Linux: Type sudo apt install default–jdk at command
4. 4
Getting Started
(2)
• After installing JDK, download Android
SDK from http://developer.android.com
• Simplest: download and install Android
Studio bundle (including Android SDK) for
your OS
• We’ll use Android Studio with SDK
included (easy)
5. Getting Started
(3)
• Install Android Studio directly (Windows, Mac); unzip to directory
android-studio, then run ./android-studio/bin/studio.sh
(Linux)
• You should see this:
5
6. Getting Started
(4)
• Strongly recommend testing with real Android
device
– Android emulator slow; Genymotion faster [14], [15]
– Install USB drivers for your Android device!
• Go to File
– Recommended: Install Android 5–8 APIs
– Don’t worry about system images for non-x86 arch.
6
8. Java Programming
Language
• Java: general-purpose
language: “write code
once, run anywhere”
• The key: Java
Virtual Machine
(JVM)
– Program code compiled
to JVM bytecode
– JVM bytecode
interpreted on JVM
• We’ll focus on Java; 8
9. 9
Our First Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println(“Hello world!”);
}
}
• Don’t forget to match curly braces { , } or semicolon at the
end!
• Recommended IDEs:
– IntelliJ IDEA CE (free; http://www.jetbrains.com/student)
– Eclipse (free; http://www.eclipse.org)
– Text editor of choice (with Java programming plugin)
10. 10
Explaining the
Program
• Every .java source file contains one class
– We create a class HelloWorld that greets user
– The class HelloWorld must have the same name as the source file
HelloWorld.java
– Our class has public scope, so other classes can “see” it
– We’ll talk more about classes and objects later
• Every Java program has a method main() that executes the program
– Method “signature” must be exactly public static void main(String[]
args) {}
– This means: (1) main() is “visible” to other methods; (2) there is “only one”
main() method in the class; and (3) main() has one argument (args, an array
of String variables)
– Java “thinks” main(), Main(), miAN() are different methods
• Every Java method has curly braces {,} surrounding its code
• Every statement in Java ends with a semicolon, e.g.,
11. 11
Basic Data Types
(1)
• Java variables are instances of mathematical “types”
– Variables can store (almost) any value their type can have
– Example: the value of a boolean variable can be either true or false
because any (mathematical) boolean value is true or false
– Caveats for integer, floating–point variables: their values are subsets of
values of mathematical integers, real numbers. Cannot assign
mathematical 2500 to integer variable (limited range) or mathematical √2
to a floating–point variable (limited precision; irrational number).
– Variable names must start with lowercase letter, contain only
letters, numbers, _
• Variable declaration: boolean b = true;
• Later in the program, we might assign false to b: b = false;
• Java strongly suggests that variables be initialized at the time of
declaration, e.g., boolean b; gives a compiler warning (null
pointer)
• Constants defined using final keyword, e.g.,
12. Basic Data Types
(2)
• Java’s primitive data types:
[5]
Primitive type Size Minimum Maximum Wrapper type
boolean 1–bit N/A N/A Boolean
char 16–bit Unicode 0 Unicode 216 – 1 Character
byte 8–bit –128 +127 Byte
short 16–bit –215
+215 – 1 Short
int 32–bit –231
+231 – 1 Integer
long 64–bit –263
+263 – 1 Long
float 32–bit IEEE 754 IEEE 754 Float
double 64–bit IEEE 754 IEEE 754 Double
Note: All these types are signed, except
char.
12
13. 13
Basic Data Types
(3)
• Sometimes variables need to be cast to another type, e.g.,
if finding average of integers:
int intOne = 1, intTwo = 2, intThree = 3, numInts = 2;
double doubOne = (double)intOne, doubTwo = (double)myIntTwo, doubThree =
(double)intThree;
double avg = (doubOne + doubTwo + doubThree)/(double)numInts;
• Math library has math operations like sqrt(), pow(), etc.
• String: immutable type for sequence of characters
– Every Java variable can be converted to String via
toString()
– The + operation concatenates Strings with other variables
– Let str be a String. We can find str’s length
(str.length()), substrings of str (str.substring()), and so
on [6]
14. 14
Basic Data Types
(4)
• A literal is a “fixed” value of a variable type
– TRUE, FALSE are boolean literals
– ‘A’, ‘t’, ‘”’, and ‘u03c0’ are char literals
(escaped tab, quote characters, Unicode value for π)
– –1, 0, 035, 0x1a are int literals (last two are octal
and hexadecimal)
– 0.5, 1.0, 1E6, 6.023E23 are double literals
– “At OSU”, “Hello world!” are String literals
• Comments:
– Single-line: // some comment to end of line
– Multi-line: /* comments span multiple lines */
15. Common Operators in
Java
String boolean char int double
! ++ --
+ || + - + -
&& * /
%
* /
< > < > < >
<= >= <= >=
== != == !=
Notes:
• Compare String objects using the equals() method, not == or !=
• && and || use short-circuit evaluation. Example: boolean canPigsFly = FALSE;
we evaluate (canPigsFly && <some Boolean expression>). Since canPigsFly is
FALSE, the second part of the expression won’t be evaluated.
• The second operand of % (integer modulus) must be positive.
• Don’t compare doubles for equality. Instead, define a constant like so:
final double EPSILON = 1E-6; // or some other threshold
… // check if Math.abs(double1 – double2) <
EPSILON
15
16. 16
Control Structures: Decision
(1)
• Programs don’t always follow “straight line” execution;
they “branch” based on certain conditions
• Java decision idioms: if-then-else, switch
• if-then-else idiom:
if (<some Boolean expression>) {
// take some action
}
else if (<some other Boolean expression) {
// take some other action
}
else {
// do something else
}
17. 17
Control Structures: Decision
(2)
• Example:
final double OLD_DROID = 5.0, final double NEW_DROID = 9.0;
double myDroid = 8.1;
if (myDroid < OLD_DROID)
{
System.out.println(“Antique!”);
}
else if (myDroid > NEW_DROID)
{
System.out.println(“Very modern!”);
}
else
{
System.out.println(“Your device: barely supported.”);
}
• Code prints “Very modern!” to the screen.
18. 18
Control Structures: Decision
(3)
• Example two:
final double JELLY_BEAN = 4.1, final double ICE_CREAM = 4.0;
final double EPSILON = 1E-6;
double myDroid = 4.1;
if (myDroid > ICE_CREAM) {
if (Math.abs(myDroid – ICE_CREAM) < EPSILON) {
System.out.println(“Ice Cream Sandwich”);
}
else {
System.out.println(“Jelly Bean”);
}
}
else {
System.out.println(“Old version”);
}
• Code prints “Jelly Bean” to screen. Note nested if-then-else, EPSILON usage.
19. Control Structures: Decision
(4)
• Other idiom: switch
• Only works when comparing an int or
boolean
variable against a fixed set of alternatives
• Example:
int api = 10;
switch (api) {
case 3:
case 4:
case 7:
case 8:
System.out.println(“Cupcake”); break;
System.out.println(“Donut”); break;
System.out.println(“Éclair”); break;
System.out.println(“Froyo”); break;
case 10: System.out.println(“Gingerbread”); break;
case 11: System.out.println(“Honeycomb”); break;
case 15: System.out.println(“Ice Cream Sandwich”); break;
case 16: System.out.println(“Jelly Bean”); break;
default: System.out.println(“Other”); break;
}
19
20. 20
Control Structures: Iteration (1)
• Often, blocks of code loop while a condition holds (or fixed # of times)
• Java iteration idioms: while, do-while, for
• While loop: execute loop as long as condition is true (checked each iteration)
• Example:
String str = “aaaaa”;
int minLength = 10;
while (str.length() < minLength)
{
str = str + “a”;
}
System.out.println(str);
• Loop executes 5 times; code terminates when str = “aaaaaaaaaa”
• Notice: if the length of str was minLength, the while loop would
not execute
21. 21
Control Structures: Iteration (2)
While Loop
String str = “aaaaaaaaaa”;
int minLength = 10;
while (str.length() <
minLength) {
str = str + “a”;
}
System.out.println(str);
Do-While Loop
String str = “aaaaaaaaaa”;
int minLength = 10;
do {
str = str + “a”;
} while (str.length() <
minLength)
System.out.println(str);
Unlike the while loop, the do-while loop executes at least once so long as condition is true.
The while loop prints “aaaaaaaaaa” whereas the do-while loop prints “aaaaaaaaaaa” (11
as)
22. 22
Control Structures: Iteration (3)
• The for loop has the following structure:
for (<expression1>; <expression2>; <expression3>) {
. . .
}
• Semantics:
– <expression1> is loop initialization (run once)
– <expression2> is loop execution condition (checked every iteration)
– <expression3> is loop update (run every iteration)
• Example:
int i;
for (i = 0; i < 10; i++) {
System.out.println(“i = ” + i);
}
System.out.println(“i = ” + i);
• What do you think this code does?
23. 23
Methods and Design-by-Contract
(1)
• Design your own methods to perform specific, well-defined tasks
• Each method has a signature:
public static ReturnType method(paramType1 param1, …
paramTypeN paramN) {
// perform certain task
}
• Example: a method to compute area of rectangle:
public static double findRectArea(double length, double
width) {
return length * width;
}
• Each method has a precondition and a postcondition
– Precondition: constraints method’s caller must satisfy to call method
– Postcondition: guarantees method provides if preconditions are met
• For our example:
– Precondition: length > 0.0, width > 0.0
24. 24
Methods and Design-by-Contract
(2)
• In practice, methods are annotated via JavaDoc,
e.g.,
/**
Compute area of rectangle.
@param length Length of rectangle
@param width Width of rectangle
@return Area of rectangle
*/
• Methods called from main() (which is
static) need to be defined static too
• Some methods may not return anything (void)
25. Array Data
Structure
• Array: fixed-length sequence of variable types; cannot change length at run-time
Examples:
final int NUMSTUDENTS = 10;
String[] students; // Declaration
String[] students = new String[NUMSTUDENTS];
// Declaration and initialization
String[] moreStudents = { “Alice”, “Bob”, “Rohit”, “Wei”};
// Declaration and explicit initialization
System.out.println(moreStudents.length) // Prints 4
• Enhanced for loop: executed for each element in
array Example:
for (String student: moreStudents) {
System.out.println(student + “, ”);
}
• Prints “Alice, Bob, Rohit, Wei,” to screen
• Array indices are numbered 0, …, N–1; watch for off-by-one errors!
moreStudents[0] is “Alice”; moreStudents[3] is 25
26. 26
Two-Dimensional
Arrays
• We can have two-dimensional
arrays. Example:
final int ROWS = 3; final int COLUMNS = 3;
char[][] ticTacToe = new char[ROWS][COLUMNS]; //
declare
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLUMNS; j++) {
ticTacToe[i][j] = ‘_’; // Initialize to ‘blank’
}
}
// Tic-tac-toe logic goes here (with ‘X’s, ‘O’s)
• ticTacToe.length returns number of rows;
ticTacToe[0].length returns number of columns
• Higher-dimensional arrays are possible too
27. 27
Parameterized Data
Structures
• We can define data structures in terms of an arbitrary variable
type (call it Item).
• ArrayList<Item>, a variable-length array that can be modified at
run-time. Examples:
ArrayList<String> arrStrings = new ArrayList<String>();
ArrayList<Double> arrDoubles = new ArrayList<Double>();
arrStrings.add(“Alice”); arrStrings.add(“Bob”); arrStrings.add(“Rohit”);
arrStrings.add(“Wei”);
String str = arrStrings.get(1); // str becomes “Bob”
arrStrings.set(2, “Raj”); // “Raj” replaces “Rohit”
System.out.println(arrStrings.size()); // prints 4
• Notice:
– Need to call import java.util.ArrayList; at beginning of program
– Off-by-one indexing: cannot call arrStrings.get(4);
– Auto-boxing: we cannot create an ArrayList of doubles. We need to
replace double with wrapper class Double. (Recall the “primitive
data types” table)
• Other parameterized data types include Lists, Sets, Maps, Stacks,
Queues, Trees (see chapters 14–16 in [1])
28. Exception Handling
(1)
• If we had called arrStrings.get(4), we
would have an error condition
– The JVM throws an IndexOutOfBounds
exception, halts execution
28
29. 29
Exception Handling
(2)
• We handle exceptions using the try-catch-finally structure:
try {
// Code that could trigger an exception
}
catch (IndexOutOfBoundsException e) { // Or another
Exception
// Code that “responds” to exception, e.g.,
e.printStackTrace();
}
finally {
// Code executes regardless of whether exception occurs
}
• There can be many catch blocks for different Exceptions, but there is
only one try block and one (optional) finally block. (See Section 7.4 in
[1] for the full hierarchy of Exceptions)
• Exceptions always need to be caught and “reported”, especially in Android
31. Objects andClasses (1)
• Classes serve as “blueprints” that describe the states and behaviors of objects,
which are actual “instances” of classes
• For example, a Vehicle class describes a motor vehicle’s blueprint:
– States: “on/off”, driver in seat, fuel in tank, speed, etc.
– Behaviors: startup, shutdown, drive “forward”, shift transmission, etc.
• There are many possible Vehicles, e.g., Honda Accord, Mack truck,
etc. These are instances of the Vehicle blueprint
• Many Vehicle states are specific to each Vehicle object, e.g., on/off, driver
in seat, fuel remaining. Other states are specific to the class of Vehicles, not
any particular Vehicle (e.g., keeping track of the “last” Vehicle ID #
assigned). These correspond to instance fields and static fields in a class.
• Notice: we can operate a vehicle without knowing its implementation “under
the hood”. Similarly, a class makes public instance methods by which objects
of this class can be manipulated. Other methods apply to the set of all
Vehicles (e.g., set min. fuel economy). These correspond to static methods in
a class
31
32. 32
Objects andClasses (2)
public class Vehicle {
// Instance fields (some omitted for brevity)
private boolean isOn = false;
private boolean isDriverInSeat = false;
private double fuelInTank = 10.0;
private double speed = 0.0;
// Static fields
private static String lastVin = “4A4AP3AU*DE999998”;
// Instance methods (some omitted for brevity)
public Vehicle() { … } // Constructor
public void startUp() { … }
public void shutOff() { … }
public void getIsDriverInSeat() { … } // getter, setter
methods
public void setIsDriverInSeat() { … }
private void manageMotor() { … } // More private methods …
// Static methods
public static void setVin(String newVin) { … }
}
33. 33
Objects andClasses (3)
• How to use the Vehicle class:
– First, create a new object via constructor Vehicle(), e.g., Vehicle
myCar = new Vehicle();
– Change Vehicle states, e.g., startUp() or shutOff() the Vehicle
– You can imagine other use cases
– Mark a new Vehicle’s ID number (VIN) as “taken” by calling
Vehicle.setVin(…)
– Caveat: VINs more complex than this (simple) implementation [7]
• Notes:
– Aliasing: If we set Vehicle myTruck = myCar, both myCar and
myTruck
“point” to the same variable. Better to perform “deep copy” of
myCar and store the copy in myTruck
– null reference: refers to no object, cannot invoke methods on null
– Implicit parameter and the this reference
34. Inheritance (1)
• Types of Vehicles: Motorcycle, Car, Truck, etc. Types of
Cars: Sedan, Coupe, SUV. Types of Trucks: Pickup, Flatbed.
• Induces inheritance hierarchy
• Subclasses inherit fields/methods from superclasses.
• Subclasses can add new fields/methods, override those of
parent classes
• For example, Motorcycle’s driveForward() method
differs from Truck’s driveForward() method
34
35. 35
Inheritance (2)
public class Vehicle {
…
public void driveForward
(double speed) {
// Base class method
}
}
public class Motorcycle
extends Vehicle {
…
public void driveForward
(double speed) {
// Apply power…
}
}
• Inheritance denoted via extends
keyword
36. Inheritance (3)
public class Truck extends Vehicle {
private boolean useAwd = true;
// . . .
public Truck(boolean useAwd) { this.useAwd = useAwd; }
// . . .
public void driveForward(double speed)
{
if (useAwd) {
// Apply power to all wheels…
}
else {
// Apply power to only front/back wheels…
}
}
} 36
37. 37
Polymorphism
• Suppose we create Vehicles and invoke the driveForward() method:
Vehicle vehicle = new Vehicle();
Vehicle motorcycle = new Motorcycle();
Truck truck1 = new Truck(true);
Vehicle truck2 = new Truck(false);
// Code here to start vehicles…
vehicle.driveForward(5.0);
motorcycle.driveForward(10.0);
truck1.driveForward(15.0);
truck2.driveForward(10.0);
• For vehicle, Vehicle’s driveForward() method is invoked
• For motorcycle, Motorcycle’s driveForward() method is invoked
• With truck1 and truck2, Truck’s driveForward() function is invoked (with all-
wheel drive for truck1, not for truck2).
• Dynamic method lookup: Java looks at objects’ actual types to find which method to
invoke
• Polymorphism: feature where objects of different subclasses are treated same way. (All
Vehicles driveForward() regardless of (sub)class.)
38. 38
The Object
Class
• Every class in Java is a subclass of Object
• Important methods in Object:
– toString(): Converts Object to a String
representation
– equals(): Compares Objects’ contents for equality
– hashCode(): Hashes the Object to a fixed-length
String, useful for data structures like HashMap, HashSet
• If you create your own class, you should override
toString() and hashCode()
39. 39
Interfaces
• Java interfaces abstractly specify methods to be implemented
• Intuition: decouple method definitions from implementations (clean design)
• Interfaces, implementations denoted by interface, implements keywords
• Examples:
public interface Driveable {
public void driveForward(double speed);
}
public class Vehicle implements Driveable {
public void driveForward(double speed) { /* implementation */ }
}
public class Motorcycle extends Vehicle implements Driveable {
public void driveForward(double speed) { /* implementation */ }
}
40. 40
The Comparable
Interface
• Comparing Objects is important, e.g., sorting in data
structures
• The Comparable interface compares two Objects,
e.g.,
a and b:
public interface Comparable
{
int compareTo(Object otherObject);
}
• a.compareTo(b) returns negative integer if a “comes
before” b, 0 if a is the same as b, and a positive
integer otherwise
• In your classes, you should implement Comparable
41. 41
Object-OrientedDesign Principles
• Each class should represent a single concept
– Don’t try to fit all functionality into a single class
– Consider a class per “noun” in problem description
– Factor functionality into classes, interfaces, etc. that express the
functionality with minimal coupling
• For software projects, start from use cases (how customers will use
software: high level)
– Then identify classes of interest
– In each class, identify fields and methods
– Class relationships should be identified: is-a (inheritance), has-a
(aggregation), implements interface, etc.
• Packages provide class organization mechanism
– Examples: java.lang.*, java.util.*, etc.
– Critical for organizing large numbers of classes!
– All classes in a package can “see” each other (scope)
43. Introduction to
Android
• Popular smartphone OS
with Apple iOS [16]
• Developed by Open
Handset Alliance, led
by Google
• Over two billion
Android smartphones in
use worldwide [17]
Source: [16]
43
45. Android Highlights
(1)
• Android apps execute on
Dalvik VM, a “clean-room”
implementation of JVM
– Dalvik optimized for efficient
execution
– Dalvik: register-based VM,
unlike Oracle’s stack-
based JVM
– Java .class bytecode
translated to Dalvik
EXecutable (DEX) bytecode,
which Dalvik interprets
45
46. 46
Android Highlights
(2)
• Android apps written in Java 6+
– Everything we’ve learned still holds
• Apps use four main components:
– Activity: A “single screen” that’s visible to user
– Service: Long-running background “part” of app (not
separate process or thread)
– ContentProvider: Manages app data (usually stored in
database) and data access for queries
– BroadcastReceiver: Component that listens for
particular Android system “events”, e.g.,
“found wireless device”, and responds
accordingly
47. 47
App
Manifest
• Every Android app must include an
AndroidManifest.xml file
describing functionality
• The manifest specifies:
– App’s Activities, Services, etc.
– Permissions requested by app
– Minimum API required
– Hardware features required, e.g., camera with
autofocus
48. Activity
Lifecycle
• Activity: key building
block of Android apps
• Extend Activity
class, override
onCreate(),
onPause(), onResume()
methods
• Dalvik VM can stop any
Activity without warning,
so saving state is important!
• Activities need to be
“responsive”, otherwise
Android shows user “App
Not Responsive” warning:
– Place lengthy operations in
Runnable Threads,
AsyncTasks 48
Source: [12]
49. App Creation
Checklist
• If you own an Android device:
– Ensure drivers are installed
– Enable developer options on device under Settings,
specifically USB Debugging
• Android 4.2+: Go to Settings→About phone, press Build number 7
times to enable developer options
• For Android Studio:
– Under File→Settings→Appearance, enable “Show tool
window bars”, “Widescreen tool window layout”
– Programs should log states via android.util.Log’s
Log.d(APP_TAG_STR, “debug”), where APP_TAG_STR is
a final String tag denoting your app
– Other commands: Log.e() (error); Log.i() (info);
(warning); Log.v() (verbose) – same 49
50. Creating Android
App
• Creating Android app
project (Android Studio):
– Go to File→New Project
– Select what kind of
Activity to create (we’ll
use Empty activity)
– Choose package name
using “reverse DNS” style
(e.g., edu.osu.myapp)
– Choose APIs for app
– Click Finish to create “Hello
World” app
50
51. Deploying the
App
• Two choices for deployment:
– Real Android device
– Android virtual device
• Plug in your real device;
otherwise, create an
Android virtual device
• Emulator is slow. Try Intel
accelerated version, or perhaps
http://www.genymotion.com/
• Run the app: press “Run”
button in toolbar
51
52. Underlying Source
Code
src/…/MainActivity.java
package edu.osu.helloandroid;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
52
}
55. A More Interesting
App
• We’ll now examine an
app with more features:
WiFi Scanner (code on
class website)
• Press a button, scan for
Wi-Fi access points
(APs), display them
• Architecture: Activity
creates single Fragment
with app logic
(flexibility)
55
56. Underlying Source Code
(1)
// WifiScanActivity.java
public class WifiScanActivity extends SingleFragmentActivity {
@Override
protected Fragment createFragment() {return new WifiScanFragment(); }
}
// WifiScanFragment.java. Uses RecyclerView to display dynamic list of Wi-Fi ScanResults.
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_wifi_scan, container, false);
mScanResultRecyclerView = (RecyclerView) v.findViewById(R.id.scan_result_recyclerview);
mScanResultAdapter = new ScanResultAdapter(mScanResultList);
mScanResultRecyclerView.setAdapter(mScanResultAdapter);
mScanResultRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
setupWifi();
mIntentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
setHasOptionsMenu(true); setRetainInstance(true);
return v;
}
private void setupWifi() {
try {
Context context = getActivity().getApplicationContext();
if (context != null) {
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}
} catch (NullPointerException npe) {
Log.e(TAG, "Error setting up Wi-Fi");
56
57. Underlying Source Code
(2)
• Get system WifiManager
• Register Broadcast Receiver to listen for WifiManager’s “finished scan” system
event (expressed as Intent
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION )
• Unregister Broadcast Receiver when leaving Fragment
@Override
public void onResume() { // . . .
super.onResume(); // . . .
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
boolean hideDialog =
sharedPreferences.getBoolean(getResources().getString(R.string.suppress_dialog_key), false);
if (!hideDialog) { // Show user dialog asking them to accept permission request
FragmentManager fm = getActivity().getSupportFragmentManager();
DialogFragment fragment = new NoticeDialogFragment();
fragment.show(fm, "info_dialog"); }
getActivity().registerReceiver(mReceiver, mIntentFilter);
}
@Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(mReceiver);
} 57
58. Underlying Source Code
(3)
• Register menu-item listener to perform Wi-Fi scan
• Get user permission first for “coarse” location (required in Android
6+)
// WifiScanFragment.java
public void onCreateOptionsMenu(Menu menu, MenuInflater
inflater) { super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu, menu); }
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_scan:
if (!hasLocationPermission()) { requestLocationPermission(); }
else { doWifiScan(); }
return true; }
return false; }
private void requestLocationPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!hasLocationPermission()) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSION_REQUEST_LOCATION); }}}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, int[]
grantResults) {
if (requestCode == PERMISSION_REQUEST_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { doWifiScan(); } else { //
58
59. The Broadcast Receiver
// WifiScanFragment.java
private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
// Override onReceive() method to implement our custom logic.
@Override
public void onReceive(Context context, Intent intent)
{
// Get the Intent action.
String action = intent.getAction();
// If the WiFi scan results are ready, iterate through them and
// record the WiFi APs' SSIDs, BSSIDs, WiFi capabilities, radio
// frequency, and signal strength (in dBm).
if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(action))
{
// Ensure WifiManager is not null first.
if (mWifiManager == null) { setupWifi(); }
List<ScanResult> scanResults = mWifiManager.getScanResults();
mScanResultList.addAll(scanResults);
mScanResultAdapter.notifyDataSetChanged();
}
}
};
59
60. User Interface
Updating UI in code
• Two inner classes handle
RecyclerView items:
– ScanResultAdapter
(extends RecyclerView.
Adapter<ScanResultHold
er>)
– ScanResultHolder
(extends
RecyclerView.ViewHolde
r)
• See code, Big Nerd Ranch
(Chapter 8) for details
UI Layout (XML)
<!-- fragment_wifi_scan.xml
(for the RecyclerView fragment) -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent” >
<android.support.v7.widget.RecyclerView
android:id="@+id/scan_result_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<!-- item_wifi_scan.xml
(for each RecyclerView item) -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content” >
<TextView
android:id="@+id/scan_result_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"/>
</LinearLayout> 60
61. Android Programming
Notes
• Android apps have multiple points of entry: no main() method
– Cannot “sleep” in Android
– During each entrance, certain Objects may be null
– Defensive programming is very useful to avoid crashes, e.g.,
if (!(myObj == null)) { // do something }
• Java concurrency techniques are required
– Don’t block the “main” thread in Activities
– Implement long-running tasks such as network connections
asynchronously, e.g., as AsyncTasks
– Recommendation: read [4]; chapter 20 [10]; [11]
• Logging state via android.util.Log throughout app is
essential when debugging (finding root causes)
• Better to have “too many” permissions than too few
– Otherwise, app crashes due to security exceptions!
– Remove “unnecessary” permissions before releasing app to public 61
62. Concurrency: Threads (1)
• Thread: program unit (within process) executing independently
• Basic idea: create class that implements Runnable interface
– Runnable has one method, run(), that has code to execute
– Example:
public class OurRunnable implements Runnable {
public void run() {
// run code
}
}
• Create a Thread object from Runnable and start() Thread,
e.g.,
Runnable r = new OurRunnable();
Thread t = new Thread(r);
t.start();
• Problems: cumbersome, does not reuse Thread 62
63. 63
Concurrency: Threads (2)
• Easier approach: anonymous inner classes, e.g.,
Thread t = new Thread(new Runnable(
{
public void run()
{
// code to run
}
});
t.start();
• Idiom essential for one-time network connections in
Activities
• However, Threads can be difficult to synchronize,
especially with UI thread in Activity, Fragment;
AsyncTasks more suitable
64. 64
Concurrency: AsyncTasks
• AsyncTask encapsulates asynchronous task that interacts with
UI thread in Activity:
public class AsyncTask<ParamsType, ProgressType, ResultType> {
protected Result doInBackground(ParamType param) {
// code to run in background
publishProgress(ProgressType progress); // UI
…
return Result;
}
protected void onProgressUpdate(ProgressType progress) {
// invoke method in Activity to update UI
}
}
• Extend AsyncTask with your own class
• Documentation at http://developer.android.com
66. 66
References (1)
1. C. Horstmann, Big Java Late Objects, Wiley, 2013. https://library.ohio-
state.edu/record=b7175998~S7
2. J. Bloch, Effective Java, 3rd ed., Addison–Wesley, 2018.
https://library.ohio- state.edu/record=b8555335~S7
3. R. Gallardo, S. Hommel, S. Kannan, J. Gordon, and S.B. Zakhour, The Java Tutorial: A Short
Course on the Basics, Addison-Wesley, 6th ed., 2015. https://library.ohio-
state.edu/record=b8554781~S7
4. C. Collins, M. Galpin, and M. Kaeppler, Android in Practice, Manning, 2011.
https://library.ohio- state.edu/record=b8534164~S7
5. M.L. Sichitiu, 2011,
http://www.ece.ncsu.edu/wireless/MadeInWALAN/AndroidTutorial/PPTs/ javaReview.ppt
6. Oracle, https://docs.oracle.com/javase/8/docs/api/index.html
7. Wikipedia, https://en.wikipedia.org/wiki/Vehicle_Identification_Number
8. Nielsen Co., “Who’s Winning the U.S. Smartphone Market?”, 6 Aug. 2013,
http://www.nielsen.com/us/en/newswire/2013/whos-winning-the-u-s-smartphone-market-
.html
9. Android Open Source Project, http://www.android.com
67. 67
References (2)
10. http://bcs.wiley.com/he-bcs/Books?action=index&itemId=1118087887&bcsId=7006
11. B. Goetz, T. Peierls, J. Bloch, J. Bowbeer, D. Holmes, and D. Lea, Java Concurrency
in Practice, Addison-Wesley, 2006, https://library.ohio-
state.edu/record=b8550371~S7
12. https://developer.android.com/guide/components/activities.html
13. https://developer.android.com/guide/topics/ui/declaring-layout.html#CommonLayouts
14. https://cloud.genymotion.com/page/doc/#collapse4
15. http://blog.zeezonline.com/2013/11/install-google-play-on-genymotion-2-0/
16. Device Atlas, https://deviceatlas.com/blog/android-v-ios-market-share#us, 9 January 2019
17. B. van der Wielen, “Insights into the 2.3 Billion Android Smartphones in Use Around
the World,” NewZoo, 17 Jan. 2018