Java - Steve Tale
Java - Steve Tale
Java - Steve Tale
This document is geared towards providing exact and reliable information in regards to the topic and
issue covered. The publication is sold with the idea that the publisher is not required to render accounting,
officially permitted, or otherwise, qualified services. If advice is necessary, legal or professional, a
practiced individual in the profession should be ordered.
- From a Declaration of Principles which was accepted and approved equally by a Committee of the
American Bar Association and a Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic
means or in printed format. Recording of this publication is strictly prohibited and any storage of this
document is not allowed unless with written permission from the publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability, in terms of
inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained within
is the solitary and utter responsibility of the recipient reader. Under no circumstances will any legal
responsibility or blame be held against the publisher for any reparation, damages, or monetary loss due to
the information herein, either directly or indirectly.
The information herein is offered for informational purposes solely, and is universal as so. The
presentation of the information is without contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without
permission or backing by the trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are the owned by the owners themselves, not affiliated with this document.
Table of Contents
Chapter 1 an Introduction to Java
History
Runtime and Performance
Syntax
Memory
Chapter 2 The Eight Primitive Types in Java
Characters
Boolean Expressions and Logic
Integers and Floating Point Numbers
Variables
Operators
Loops
Switch Case
Chapter 3: Arrays and Strings
Arrays
Strings
How to Format Java Strings
Chapter 4: Primitive VS Reference Types
User Datagram Protocol
Transmission Control Protocol
Internet Control Message Protocol
Address Resolution Protocol
Internet Protocol
Chapter 5: Object Oriented Programming
Chapter 6: How to make your own classes
Framework for Java Classes
Turning Classes into Pages
The Headings
Paragraphs
Images
Links
Elements
How to Quote Properly
Long Quote
Short Quote
Contact Information Quote
Java Plus CSS
Important Elements
Internal Styling (Internal CSS)
Inline Styling (Inline CSS)
External Styling (External CSS)
CSS Fonts
Chapter 7: Fields, Methods, and Constructors
Fields
Methods
Constructors
Destructors
Getting Peer Information
Network I/O Methods
Encapsulation
Abstraction Layers
Inheritance
Internet Model
Patterns
Stream Class
Polymorphism
Adding Directives
Adding Controllers
File Polymorphism and Controllers
Loading the Library
Chapter 9 Abstract Classes and Interfaces
Filters
Expression Filters
Currency Filters
Directive Filters
Filter Filter
More about Interface
JSON Object
Services
Chapter 10 Conditional and Control Flow Statements
Conditional Statements
Java Forms
Control Flow Statements
Chapter 11 Dealing with Errors and Exceptions
Understanding Acceptor Classes
Correcting Statements and Arguments
Debugging and Exception Handling
Conclusion
Bonus: Preview Of SQL The Ultimate Beginners Guide Learn SQL Today
Thank you again for downloading this book!
Introduction
Known as one of the most useful, general purpose, object-oriented languages around, Java is one of the
best programming languages that you could learn aboutand even master, even if you're just a beginner!
With the help of this book, you would be introduced to what Java is about, its primitive types, data types,
how object oriented programming actually worksand more!
Start reading this book now and you'll learn more about Java in no time!
Once again, thank you, and enjoy!
Chapter 1 an Introduction to Java
More than anything, what you have to understand about Java is that it is a general purpose, object-oriented
programming languagewhich means that it is easier to understand than other programming languages.
It was designed primarily so that software developers could just code their programs once, and allow
those programs run anywhere, or at least, in most platforms, as long as those platforms allow Java code
to run in them.
Java primarily uses some of the same elements that C+ and C++ use, but transforms them into much
simple, easy to understand versions that could also be modified depending on the developers preferences.
Java has also been created to run with enough runtime support, both for hardware and software, by means
of representing each bytecode in a clear, and concise manner. For example, shih tzus, border collies, and
terriers are all dogstherefore, they could all be classified as dogs, and thus, not a lot of space would be
taken up in the system, and the system would be able to work in a fast manner. This is also the reason
why Java is one of the worlds most powerful, and most used programming languages of all time!
History
The history of Java dates back to 1991 when programmers Patrick Haughton, Mike Sheridan, and James
Gosling thought of a programming language that could best be used for the development of Digital TV.
However, it was deemed to be way ahead of its own time, and thus, they redeveloped it based on the C+
and C++ platforms to make it easier and more economical to use.
With the redevelopment also came the core principles of Java, which are:
1. It has to be portableor that it should work on as many platforms as possible, without any of
them not working as well as the other;
2. It should be safe and secure to useand definitely well encrypted;
3. People should feel connected to it in as little time as possible, which means that they should be
working with words that are somehow familiar to them, and even though it looks complex at
first, sooner or later, they have to realize that it actually works;
4. It should be dynamic, should work in threads, and could be modified when needed, and;
5. It should perform with precision.
As you can see, these core principles give you the feeling that the programmers real made Java for the
peopleso they can enjoy using more programs without having to buy too many devices.
In 1995, Sun Microsystems finally released Java 1.0the first public inception of Java, which had
amazing security, no-cost runtimes, and file access restrictions across all networks. Over the years, 7
more Java releases had been made, and ever since 2006, Java started to be available through GNU, or
General Public Licensemeaning it is now a free, open-source programming language. This stemmed
from the public outcry that happened once when some of its contents were made private and only
available for a fee, which definitely does not resonate with its core principles.
Memory
Another reason why Java works fast is because it makes use of Automatic Memory Management, which
means that runtime won't be affected by what the programmer chooses to add or subtract from what he's
trying to create.
Now, what happens is that when there are no more references to a certain object, it would no longer be
considered as part of the program, and won't be using a lot of memory, toomaking the program easier
to manage altogether.
It's now time to learn more about Javaread the next chapters, and understand how this works!
Chapter 2 The Eight Primitive Types in Java
As mentioned earlier, there are eight primitive, or original data types in Java programming. Here they
are, and what you should know about them.
Characters
Characters compose the first primitive types of Java. Basically, these are the words that you should be
using while creating your program. These also encompass a lot of things, and these are
1. If. This executes block codes, and includes (else and elif)
2. While. This is used for true conditions, and also executes block codes.
3. For. This is used for attached blocks.
4. Try. This is handled by except and allows raised exceptions for code blocks.
5. With. This makes use of block managers, and helps open and close files.
6. Def. This means that a method or function is defined.
7. Class. This executes block codes and is used for object-oriented programming.
8. Print/ Print(). This is used for printing.
9. Import. This is used to import modules from other functions.
10. Yield. This is used to generate function values and is also used as an operator.
11. Assert. This is used to check statements that are meant to be applied.
12. Pass. This is used to create empty code blocks.
Take note that these keywords cannot be used as variables!
Indentation and Lines
The number of spaces and words used would determine whether what you have programmed is right, or
if it would generate errors:
Take a look at the two examples below. The first one is right, while the other generates an error because
of the un-indented print command at the last line.
Example 1:
if True:
print "True"
else:
print "False"
Example 2:
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Quotations
To create quotations in this program, take note that you could use single (), double, () or triple ( )
notes to indicate strings and literal strings.
For example:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments
To create comments, just use hashtag (#)this really sounds like its social-media friendly, huh? For
example:
Example 1:
#!/usr/bin/java
# First comment
print "Hello, Java!" # second comment
Example 2:
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Conditional Execution
Theres also such a thing as conditional execution, or the means to change behavior and check conditions
that affect the programs behavior. This makes use of the If Statement. Heres a good example:
if x % 2 == 0:
print(x, " is even.")
print("Did you know that 2 is the only even number that is prime?")
else:
print(x, " is odd.")
print("Did you know that multiplying two odd numbers " +
"always gives an odd result?")
Thisll give you this result:
f BOOLEAN EXPRESSION:
STATEMENTS_1 # Executed if condition evaluates to True
else:
STATEMENTS_2 # Executed if condition evaluates to False
Chained Conditionals
Else If/ If Else are important in this conditional. Heres an example:
if choice == "a":
function_one()
elif choice == "b":
function_two()
elif choice == "c":
function_three()
else:
print("Invalid choice.")
Nested Conditionals
There are also Nested Conditionals which basically mean that conditionals could stay on top of the other.
For example:
if x < y:
STATEMENTS_A
else:
if x > y:
STATEMENTS_B
else:
STATEMENTS_C
You can also simplify this by doing the following:
if 0 < x: # Assume x is an int here
if x < 10:
print("x is a positive single digit.")
Remember that print can only be used once it passes both of the conditionals, which means:
if 0 < x and x < 10:
print("x is a positive single digit.")
Omitting Else Clause
The Else Clause could also be omitted if a condition is evaluated as true. For example:
if x < 0:
print("The negative number ", x, " is not valid here.")
x = 42
print("I've decided to use the number 42 instead.")
result = x**0.5
print("The square root of", x, "is", result)
Also, make sure that you use an uppercase L so that the program would not think if lowercase l as the
number 1.
You can also use commas to assign single values in a synchronized manner. For example:
a=b=c=1
Variables
Next, its time for you to learn Java Variables.
Before you go and wonder what Variables are, what you have to know is that theyre basically means to
store memory valueswhich means youre using the program to determine where to keep what you have.
Here, youll be using a lot of decimals, integers, and various kinds of characters, too!
Before learning the commands, here is a crash course on Data Type Conversion first.
Data Type Conversion
1. Int (x [,base]). If x is a string, it becomes the base; also converts x to an integer.
2. Float (x). Converts integers into floating numbers.
3. Long (x [,base]). Converts x to long integers.
4. Str (x). converts x to string representation.
5. Complex (real [,imag]). This gives you a complex number.
6. Eval (str). This evaluates a string and gives you an object in return.
7. Repr (x). Converts x to repression string.
8. Set (s). Converts x to set.
9. List (L). Converts x to list.
10. Tuple (t). Converts x to tuple.
11. Frozen set (s). Converts x to frozen set.
12. Dict (d). This gives you a dictionary.
13. Oct (x). Converts x to octal string.
14. Hex (x). Converts x to hexadecimal string.
15. Ord (x).This gives a single character its integer value.
16. Unichr (x). And finally, with this command, youll get a Unicode character.
Value Assignation
The equal sign (=) is important here because. You do not need to make explicit declarations here but you
have to make sure that you place the variable before the equal sign, and on the right, put what you want
to happen to the variable. For example:
#!/usr/bin/java
print counter
print miles
print name
This would then give you the result of:
100
1000.0
John
Operators
Then, you also have Java Operators. These manipulate operand values, and could be categorized as:
1. Arithmetic
2. Assignment
3. Identity
4. Membership
5. Bitwise
6. Logical
7. Comparison/ Relational
Arithmetic Operators
Here are the arithmetic operators that you can use:
1. + Addition. Of course, this adds values on your operators ( a + b = 15)
2. Subtraction. This subtracts the operand on the right from the one on the left. (a b = -10)
3. /Division. This divides operand on the left with whats on the right. (b/a = 2)
4. *Multiplication. Multiples whatever you have. (a * b = 200)
5. // Floor Division. With this, youd get quotient results, especially when decimal points are
removed. (9//2 = 4) (9.0//2.0 = 4.0)
6. **Exponent. This helps you derive exponential notation. (a**b = 5 to the power of 10)
7. % Modulus. Divides operand on the left by the right and provides remainder. (b% a = 0)
Assignment Operators
1. =. Gives value to whats on the right side back to the left operand. (c = a + b assigns value of a +
b into c)
2. -=Subtract AND. This subtracts the operand on the right from the left operand and assigns results
to whats on the left. (c -= a is equivalent to c = c a)
3. +=Add AND. This adds the operand on the right to the left and gives left operand result. (c += a
is equivalent to c = c + a)
4. /=Divide AND. Divides left with right operand and assigns value to the left. (c /= a is equivalent
to c = c / ac /= a is equivalent to c = c / a)
5. *=Multiply AND. Multiplies right operand with left operand and assigns result to left operand.
(c *= a is equivalent to c = c * a)
6. **=Exponent AND. Derives exponential notation. (c **= a is equivalent to c = c ** a)
7. %=Modulus AND. Takes modulus of two operands. (c %= a is equivalent to c = c % a)
8. // Floor Division AND. With this, youd get quotient results, especially when decimal points are
removed. (c //= a is equivalent to c = c // a)
Identity Operators
These compare memory of two locations of two different objects.
1. Is. Determines whether variables on either side are true; if not, operator points to the same
subject. (x is y, here is results in 1 if id(x) equals id(y).)
2. Is not. If variables on either side are false, operator points to the subjects and says true-wise. (x
is not y, here is not results in 1 if id(x) is not equal to id(y).)
Membership Operators
These check whether there is membership or coherence in a certain sequence.
1. Is. Checks whether variables on each side are true. (x is y, here is results in 1 if id(x) equals id(y).)
2. Not in. Checks if a variable is not in a specified sequence and evaluates to either true or false. (x
not in y, here not in results in a 1 if x is not a member of sequence y.)
Bitwise Operators
These perform bit by bit operation. For example:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Logical Operators
Logical Operators are basically items that hold 10 to 20 variables in between them.
Comparison Operators
1. ==. Condition equates to true if the operands are equal. ((a==b) is not true)
2. <>. If values are not equal, condition becomes true. ((a<>b) is true)
3. !=. Condition becomes true if values of two operands are not equal.
4. <=. Condition becomes true if left operand value is less than the right operand. (a <=b) is true)
5. >=. Condition becomes true if value of left operand is greater than right operand. (a>=b) is not
true)
6. <. If left operand value is less than right operand, condition is true. (a < b) is true)
7. >. If value of left operand is greater than right, condition is true. ((a>b is not true)
Loops
Loops are statements that provide various actions that could be used in your program. These include:
1. For Loop. This helps you execute statements a number of times and also abbreviates codes
that are used in the variable.
2. While Loop. This repeats statements or groups of statements that you want to use again in your
program.
3. Nested Loop. This means that youre using one or more loops in your program.
4. DoWhile Loop. This is equivalent to a statement but is seen by the program as a condition.
5. Goto Statement. This gives control to the statement that has already been labeled.
6. Continue Statement. This helps the loop skip the remainder of the bodyso it wouldnt be
around when its unnecessary.
7. Break Statement. This terminates the switch and loop statements and helps execute the other
statements in the program after you have made one of the loops.
Switch Case
And of course, if you want to test variables, you have to make use of switch casesalso known as
switch statements. There are certain rules that you have to follow, though, and these are:
1. Switch statements could also be default cases. Therefore, they have to appear at the end of the
switch and could be used to determine false statements in the program. In this case, you
wouldnt have to use a break anymore.
2. You dont need a break for every case. In case no break appears, all you have to do is wait for
something to fall through.
3. When you have reached the break statement, go ahead and change the terminates that you have
been using so that you could then jump to the next line.
4. Constant Expression should be used. This means you have to use the same data types in your
program.
5. Every switch contains a number of case statements that could be separated with colons.
6. You could use enumerated or integral types of switches so that class conversion could easily be
done.
For this, you have to remember that:
ExpressionCase 1 Code Block 1
Case 2 Code Block 2
Case 3 Code Block 3
And so on. In short, you could take note of the example below:
#include <mylistofgrades>
int main () {
/* local variable definition */
char grade = 'D';
switch(grade) {
case 'E' :
printf("Amazing!/n" );
break;
case 'E' :
case 'D' :
printf("Great Job!\n" );
break;
case 'D' :
printf("You did well!\n" );
break;
case 'F' :
printf("Try again next time\n" );
break;
default :
printf("Invalid grade\n" );
}
return 0;
}
Chapter 3: Arrays and Strings
In Java, arrays and strings help make sure that whatever will appear onscreenor on the finished
program are certainly what the programmer, or you, in this case, want to express .
In coding the Java language, you of course have to make use of expressions. These are written in double
braces {{}}, but could also be contained within a directive, just like this one below:
Ng-bind= expression
The expression will then be resolved by Java itself, and have results returned when they are ready. They
pretty much mirror JavaScript expressions, so if you know something about that, this language would
not be too hard for you.
This also means that Java Expressions are:
1. Java Expressions could contain filtersbut JavaScript expressions do not have them.
2. They do not support exceptions, loops, and coordinates.
3. The expressions could be written inside HTML.
4. Java Expressions could also be variables, operators, and literals.
For example:
{{ 10 + 5 }} or {{ name + " " + nickname }}
This means that a basic Java expression code would look like the following:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="">
<p>Supergirl Versus Bizarro: {{ Supergirl +Bizzaro }}</p>
</div>
</body>
</html>
By taking away the ng directive, HTML would not be able to solve the expression, but just show it as it
is, which would just basically look the same as this:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="">
<p>Supergirl Versus Bizarro: {{ Supergirl +Bizzaro }}</p>
</div>
</body>
</html>
Another example would be if you want to change certain colors and styles in CSS. For example, if you
want to change the color of a box as pink, you could try the following:
<div ng-app="" ng-init="myCol='pink'">
</div>
Arrays
This works like JavaScript Arrays. If youre going to use ng-bind, it would look something like this one
below:
<div ng-app="" ng-init="points=[2,4,6,8]">
</div>
But, if youre going to take away ng-bind, it would look something like this one:
<div ng-app="" ng-init="points=[2,4,6,8]">
</div>
Strings
Strings connect things together, even in programming. Java Strings also work like JavaScript. It could
go two waysjust take a look at the examples below:
<div ng-app="" ng-init="firstName='Mark';lastName='Ruffalo'">
</div>
Or:
<div ng-app="" ng-init="firstName='Mark';lastName='Ruffalo'">
</div>
6. Double and Float. This is used to indicate float type variables and are used for respective data. For
example:
Float thisvariable
Double thisvariable
7. Do and While. This is used for looping the C Program. Heres an example:
i=7;
while (i<7) {
print("%d ",i)
i++;
}
That will then give you the following output: 0 2 4 6 7 9
8. Extern. This denotes that external variables are around and is accessed and declared through different
functions. For example:
#include <myfavoriteprogram>
extern i=8;
void print1(){
printf ("%d ",i);
}
int main() {
printf("%d ",i);
}
return 0;
}
9. Enum. As the name suggests, this is used to enumerate certain parts of the program. This consists of
constant integers. For example:
enum enum_var{
var4;
var5;
var6;
};
10. If and Else. These two go together and is usually used for decision-making purposes. For example:
if (i==2)
printf("i is 2.")
else
prinf("i is not 2.")
11. Goto. This is used for labeled statements for unconditional jumps. For example:
for(i=1;i<6;++i){
if (i==10)
goto error;
}
printf("i is not 9");
error:
printf("Error, count can't be 9");
12. For. This is used for C Loops. Heres an example:
for (i=0;i<1;++i){
printf("%c ",i);
}
13. Short, long, unsigned. These are mostly used for integers, and for this, you have to take note of the
following ranges:
Short int (-32768 to 32767)
Unsigned int ( 0 to 655355)
Signed int (-32768 to 32767)
Long int (-32768 to 32767)
14. Sizeof. This is used to determine the size of something on your program. Heres an example:
#include <stdio.h>
int main(){
printf("%u bytes.",sizeof(char));
}
15. Return. This terminates the current functions execution and gives some value back to the function
itself. For example:
int func(){
int b=10;
return c;
}
16. Static. This is used to indicate the storage class value and could be used until you reach the end of
the program. For example:
Static int var;
17. Register. This is something that differentiates normal variables from fast ones. For example:
Register int var1;
18. Typedef. This helps you differentiate simple numbers from integers. For example:
Typedef float ab;
Ab butterfly, wings
19. Struct. This is used to create structures so they could easily be managed. For example:
struct contestant{
char name[1116];
float marks;
int age;
}s2,s3;
20. Void. This means that a part of your program has no value. For example:
void no_return(int a){
.....
}
21. Union. Union is about handling the variables. This is what you have to do:
union student {
char name[100];
float marks;
int age;
}
22. Volatile. This means that you have an erroneous function in your program. This is what you have to
do:
const volatile number
There are also special characters that you can use, and these are:
, <> . _ () ; $ : % []# ? & {} ^ ! * /|-\~+
As for digits, you can use the following:
0123456789
You can also use uppercase or lowercase alphabet letters, as well.
Chapter 4: Primitive VS Reference Types
Earlier, you learned about the primitive or independent data types in Java. You also have to know,
though, that there are also things called reference types, and just like primitive ones, these are also in
different categories and could do a lot of thingsbut have to be supported by primitive data.
Are primitive data types better than those in the reference category? Not entirely. While Primitive types
could stand on their own, there are certain things that reference data types can do that can make the
program that you are trying to make a whole lot better.
What exactly are these types?
User Datagram Protocol
This is an important member of the Internet Protocol Suite. It provides connectionless transmissions in
such a way that they could actually be reliable, and that they would not ruin the protocol of the network
in any way. They are perfect for time-sensitive applications that easily drop pockets. User Diagram
Protocols are also:
1. It is capable of providing datagrams to the network;
2. It is transaction-oriented and work for both Network Time Protocols and Domain Name Systems;
3. It works with unidirectional communication, which is suitable for service discoveries and broadcast
information;
4. It works for real-time applications (such as Twitter, Snapchat, Periscope, etc.) because it makes way of
transmission delays. It also works for VOIP applications (such as Skype), and works for some games, as
well;
5. It is suitable for a large number of clients, and is stateless. It also works for streaming applications, and;
6. Its perfect for bootstrapping because it is simple and stateless.
It also works for Octets 0 to 4, and even 20 to 160 in some cases.
Transmission Control Protocol
This provides error-checked, orderly, and reliable stream of octets between the IP Network and the
various networks that it contains. This is used for email, and most of the World Wide Web, as well. This
is also a latent, connectionless protocol, and works by processing data that has already been transmitted.
It works from octets 0 to 160, containing source and destination ports. It also contains sequence numbers,
and acknowledgment numbers.
Data Offset is also reserved, together with window size, checksum, and urgent pointers, as well.
Basically, what you can keep in mind is:
1. 16 bits identify the source port;
2. 16 bits also identify the receiving port;
3. 4 bits specify the data header in 32-bit words;
4. 32 bits identify the acknowledgment numbers;
5. 9-bits contain the 9-bit flags;
6. 3 bits define data that is reserved for future use.
Other bits define options that you could create for your app or website using this programming language.
Internet Control Message Protocol
Another important protocol of JAVA, this one could send requested services and messages to the router,
and also has its own protocol number. The difference is that it starts in the IPv4 Header, and is mostly
just known as 1. It also works between octets 0 to 4, where:
1. Code = Control Messages | ICMP Subtype
2. Type = Control Messages | ICMP Subtype
3. Rest of Header = Contents | ICMP Subtype
4. Checksum = Error Checking Data | ICMP Header and Data
Data then derives a section in IPv4 where error-checking is done. Implementations are also accessible
through APIs and various kinds of sockets, together with Network Discovery Protocols and
microcontroller firmware.
</body>
</Java>
Take note that declarations would differ depending on the Java type that youre using. This means that
you have to do the following:
1. XJava 1.0: <!UNICODE Java PUBLIC "-//W3C//DTD XJava 1.0 Transitional//EN"
"http://www.w3.org/TR/xJava1/DTD/xJava1-transitional.dtd">
2. Java 4.01: <!UNICODE Java PUBLIC "-//W3C//DTD Java 4.01 Transitional//EN"
"http://www.w3.org/TR/Java4/loose.dtd">
3. Java 5: <!UNICODE Java>
The Headings
Of course, your pages need headings. These work like subheadings in books or articles so youd know
exactly what goes on in a pagewhat its about, in other words.
Headings range from <H1> to <H6>. Heres a good example:
<h1>Look at my heading</h1>
<h2>Look at my heading</h2>
<h3>Look at my heading</h3>
<h4>Look at my heading</h4>
<h5>Look at my heading</h5>
<h6>Look at my heading</h6>
Paragraphs
Paragraphs are also used in webpages as well as in articles and novels. Youll know that a paragraph is
around when the <p> tag is in. This also makes it easier for you to read whats on the page.
Without the use of paragraphs, everything would be cramped in one space alongmaking them
extremely hard to read. For this, you could try the following:
<p>Read this paragraph.</p>
<p>Read one more paragraph.</p>
Images
Images could also be used to spruce up your website. It makes people want to read the website more
because images always makes things easy on the eyes. This means youd have to use the <img> tag for
this.
The attributes of this are as follows:
1. alt (alternate text)
2. src (image source)
3. size (width and height)
For example:
<img src="chanel1.jpg" alt="chanel2" width="104" height="142">
Links
And of course, the use of links is also encouraged. These are defined with the <a> tag. It makes things
easy on the eyes so that everything wouldnt be on one page alone, and readers could be taken to
different pages on your website.
Heres a good example:
<a href="http://thechanels.com">See this link</a>
Elements
Various elements are also used in an Java page. If you could remember, pairs of tags are always used in
a webpage thats been coded with Java.
It should look something like this:
<tagname>tagname</tagname>
For example:
<h1> Read this heading </h1>
<p> Have you seen the light? </p>
<b><p>What is feminism?</b></p>
So basically, the whole program is depicted through various <Java> tags, and thats why start <> and
end </> tags have to be used. Without them, words on the page would all come togethermaking them
hard to read. The <body> tag then defines what the page contains. It also contains headings, paragraphs,
and other attributes.
For example:
<Java>
<body>
<h1>My Sunday</h1>
<p>Last Sunday was the best Sunday because we went to the park and flew kites.</p>
</body>
</Java>
With the help of start and end tags, you get to understand whats being shown onscreen. They give a
page a lot of meaninginstead of it being just mumbo-jumbo.
Other important elements are the headings <h1>, and paragraphs </p> so that headings could also be
defined. A sample of headings are as follows:
<h1> See how awesome this is </h1>
<h2> Have you seen where she went? </h2>
<h3> Where will you go next? </h3>
<h4> what will you watch? </h4>
<h5> what are you listening to? </h5>
<h6> what are you going to eat? </h6>
In between those headings, you could write what you have in mindwhich then would give the
webpage a better, more believable look! For example:
<h1> See how awesome this is </h1>
<p> I see how awesome this is and I like it </p>
<h2> Have you seen where she went? </h2>
<p> No, I have no idea where she went </p>
<h3> Where will you go next? </h3>
<p> Im planning to go to Chicago, then maybe do a side trip to New York to catch a show on
Broadway </p>
<h4> what will you watch? </h4>
<p> Lion King or Cats </p>
<h5> what are you listening to? </h5>
<p> Im listening to the new Selena Gomez record. So far, so good </p>
<h6> what are you going to eat? </h6>
<p> Im going to eat some omelet and buttered vegetables </p>
See how much of a difference that makes?
You should also keep in mind that there are such things as empty Java elements. This basically pertains
to the br tag <br> which also depicts a line break. Its pretty much like a space, if youre goiung to think
of articles or books.
For example:
<h1> See how awesome this is </h1>
<br></br>
<p> I see how awesome this is and I like it </p>
<h2> Have you seen where she went? </h2>
<br></br>
<p> No, I have no idea where she went </p>
<h3> Where will you go next? </h3>
<br></br>
<p> Im planning to go to Chicago, then maybe do a side trip to New York to catch a show on
Broadway </p>
<h4> what will you watch? </h4>
<br></br>
<p> Lion King or Cats </p>
<h5> what are you listening to? </h5>
<br></br>
<p> Im listening to the new Selena Gomez record. So far, so good </p>
<h6> what are you going to eat? </h6>
<br></br>
<p> Im going to eat some omelet and buttered vegetables </p>
Also, you have to remember that while tags are not case-sensitive, its still better to use lowercase tags
especially in Java 4 and 5which are commonly used these days. This way, youd avoid problems from
happening to your page.
Long Quote
For example, you have created a new website for fostering and taking care of animals, and you are
affiliated to the WWF (World Wildlife Fund). This means you may have to quote from their website. How
would you do this?
Well, you can use the Long Quote Style. This is depicted by <blockquote>, which would then indent the
passage. So, if you have quoted this way:
<p>Here is a quote from WWF's website:</p>
<blockquote cite="http://www.worldwildlife.org/who/index.Java">
For 50 years, WWF has been protecting the future of nature. The leading conservation
organization in the world,
WWF works in over 100 countries and is supported by all
1.2 million members in the US and
close to 5 million globally.
</blockquote>
What youd see onscreen is something like this:
Here is a quote from WWF's website:
For 50 years, WWF has been protecting the future of nature. The world's leading
conservation organization, WWF works in 100 countries and is supported by 1.2 million
members in the United States and close to 5 million globally.
Short Quote
For short quotes, you could try using <q>. For example:
<p>ABC123s Goal is to: <q>Build a future where people know how to code without problems,
and create the websites they want.</q></p>
Important Elements
1. Style. Internal Styling
2. CSS Margin. Space outside the border
3. CSS Padding. Space inside the border
4. CSS Font-Size. This determines text sizes
5. CSS Font-Family. This determines where the font came from
6. CSS Color. This determines the color of font being used
7. <head>. This refers to elements of <link> and <style>
8. <link>. A link to external CSS files
9. <style>. The style of internal CSS
</body>
</Java>
</body>
</Java>
CSS Fonts
Finally, in order to easily change fonts, make sure that you know how to differentiate elements. Color
determines the Java text color in the page, font-size is all about the size of font used, and font-family
defines which family the font came from (i.e., serif, sans serif, etc.)
<!UNICODE Java>
<Java>
<head>
<style>
h1 {
color: blue;
font-family: serif;
font-size: 100%;
}
p {
color: red;
font-family: courier;
font-size: 120%;
}
</style>
</head>
<body>
</body>
</Java>
Now that you know the basics, you could finally create your own website!
Chapter 7: Fields, Methods, and Constructors
Next, it's time for you to learn about certain elements that could strengthen the program that you are
trying to develop, and these are fields, methods, and constructors.
Fields
Fields basically are just the scopes that Java encompass. With these fields come terms that would help
you understand what they're really about. By knowing these terms, it would be easy for you to know what
youre dealing withand coding wouldnt ever be a problem.
For this, you could take note of the following terms:
Ng-bind. This means that DOM element texts are being set. This means that the value of the name
would be seen inside the span element. Any changes made to the name would directly reflect on other
elements of the DOM. For example:
<span ng-bind="name"></span>
Ng-app. This derives the Java s root element so that behavior and directives would be defined, as well.
Ng-model-options. This allows updates for the model to be done by means of fine tuning.
Ng-model. This is almost the same as Ng-bind so that thered be a bond between the scope and the view.
Ng-controller. This means that HTML expressions are evaluated with the help of the JavaScript
controller class.
Ng-class. These are dynamically-loaded class attributes.
Ng-show and Ng-hide. This shows or hides the elements conditionally, which always depends on the
Boolean expression formula. This could be achieved by using CSS styles.
Ng-repeat. This instantiates elements for a collection at least once.
Ng-view. This is responsible for handling ON routes for the base directives which are also specified by
certain controllers.
Ng-switch. This helps you choose from a set of templates depending on the values of the expressions.
Ng-animate. This helps provide enough support for CSS3 Keyframe, CSS3 Transition, and JavaScript.
This also provides enough custom and core directives, together with animation keyhooks, too.
Ng-aria. This one creates common ARIA attributes, and also serves as a module of accessibility and
support.
Arguments = Scopes
In Java Programming, Scopes are equivalent to arguments. This happens because scopes bind JavaScript
and HTML Element, which means that at some point, there would be some form of conflict, too.
Scopes have available methods and abilities, and are available for both controller and the view. The view
depicts HTML, while controller is JavaScriptwhich is the one responsible for controlling, editing, or
deleting data.
Scopes are also models with both properties and methods available for the user to use. It means that when
changes are made, both controller and view will be affectedand updated.
Here are some examples:
<div ng-app="TheHungerGames" ng-controller="myCtrl">
<h1>{{TheHungerGames}}</h1>
</div>
<script>
var app = Java .module('myApp', []);
app.controller('movies', function(Rscope) {
Rscope.thehungergames= "TheHungerGames";
});
</script>
<div ng-app="TheHungerGames" ng-controller="myCtrl">
<input ng-model="thehungergames">
<h1>Movie is {{thehungergames}}</h1>
</div>
<script>
var app = Java .module('myApp', []);
app.movies('myCtrl', function(Rscope) {
Rscope.name = "thehungergames";
});
</script>
Rooting Mechanisms
Theres also such a thing as Rooting Mechanism (also known as $rootscope). This uses the ng-app
directive and is available for the whole applicationso you can say that its a really important part of
the tutorial. This also uses the scope thats currently used.
For example:
<body ng-app="TheFirstApp">
<p>The rootScope's favorite color:</p>
<h1>{{pink}}</h1>
<div ng-controller="myCtrl">
<p>The scope of the controller's favorite color:</p>
<h1>{{purple}}</h1>
</div>
<p>The rootScope's favorite color is still:</p>
<h1>{{pink}}</h1>
<script>
var app = Java .module('TheFirstApp', []);
app.run(function($rootScope) {
$rootScope.color = 'pink';
});
app.controller('myCtrl', function(Rscope) {
Rscope.color = "purple";
});
</script>
</body>
Limiting Areas
You also should understand where the scopes begin, and when they end. This will make your program
more coherent, and help you understand what needs to be done. Its like knowing whats going on around
you so you could easily deal with them. This is not usually an issue unless youre dealing with large DOM
Applications. The ng-repeat directive is essential for this one.
For this, you could follow the code below:
<div ng-app="TheFirstApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in thefirstapp">{{x}}</li>
</ul>
</div>
<script>
var app = Java .module('TheFirstApp', []);
app.controller('myCtrl', function(Rscope) {
Rscope.names = ["the", "first", "app"];
});
</script>
Methods
Meanwhile, and as the name suggests methods are about the actions you should take in filling up those
fields, and making sure that your program would be as coherent and as well out, as possible.
Methods, in Java, are known as information payloads that are responsible for sending data from the
application to its own store, which could then be sent with the syntax store.dispatch () and are known to
be plain JavaScript objects, and that is why the type property has to be used, and that types should then
be considered as string constants. If you have an app thats already large enough, it can then be moved to
a separate module.
However, you have to keep in mind that methods dont have to be depicted in separate files. In fact, you
might not even have to define them at all, but you do have to declare their codebases, and understand the
right type of syntax to be used.
For example:
const ADD_TODO = 'ADD_TODO'
type: SET_VISIBILITY_FILTER,
type: ADD_TODO,
text: Welcome to My First App
filter: SHOW_COMPLETED
}
}
Action Creators
True to the name, Action Creators are the kind of functions that are able to create methods, or have
methods returned to the user. They create valuable dispatches when invoked, and promote bound
methods.
Dispatches or dispatch () is something that you could directly access from the store, and provide
connection between Java and the reader, also known as Java-reader collect. These action creators could
also have certain side effects, which are also known as methods of synchronicity and AJAX Responses.
Heres a sample proper code:
function addTodo(text) {
type: ADD_TODO,
type: ADD_TODO,
text
text
return {
function addTodoWithDispatch(text) {
dispatch(completeTodo(index))
dispatch(addTodo(text))
dispatch(action)
const boundCompleteTodo = (index) => dispatch(completeTodo(index))
const boundAddTodo = (text) => dispatch(addTodo(text))
const action = {
boundCompleteTodo(index)
boundAddTodo(text)
}
}
Source Code
To code this properly, do make use of the following source code:
/*
* action types
*/
SHOW_COMPLETED: 'SHOW_COMPLETED',
SHOW_ALL: 'SHOW_ALL',
SHOW_ACTIVE: 'SHOW_ACTIVE'
return { type: TOGGLE_TODO, index }
return { type: SET_VISIBILITY_FILTER, filter }
return { type: ADD_TODO, text }
export function toggleTodo(index) {
export function setVisibilityFilter(filter) {
export function addTodo(text) {
export const VisibilityFilters = {
export const TOGGLE_TODO = 'TOGGLE_TODO'
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'
export const ADD_TODO = 'ADD_TODO'
}
* other constants
* action creators
Constructors
And of course, there are also constructors that help connect everything, bind them together, and make
your program work effectively even with different elements involved.
Constructors allow the connect() method to happen and to be prevalent in the program. This contains the
names of the IP, together with the hosts and is usually returned to the sender, or caller. To code, just follow
what you see below:
#include <netinet/in.h>
#include "Javastream.h"
class FirstJavaConnector
{
public
JavaStream* connect(int port, const char* server);
private:
int resolveHost(const char* host, struct in_addr* addr);
};
You also have to take note that connected to the descriptor of the socket that allow peer Java Ports and
peer IP Addresses to show up onscreen. Take note that this does not use other languages, except for C++,
unlike its contemporaries in Java.
For this, you have to use the following syntax:
JavaStream::getPeerIP()
JavaStream::getPeerPort()
To code, just follow what you see below:
#include <arpa/inet.h>
#include "newJavastream.h"
There are also Java elements that help determine how your program could be edited, and how it would
appear when seen by others. These also encompass the depth of the programor its heart, in other
words. You can learn more about these below:
Encapsulation
First up is encapsulation, which makes use of a coupe of principles to be executed well. These Principles
are:
1. Robustness Principle. This means that protocols have to be implemented but sending behavior has
to be conservative, while receiving behavior should definitely be liberal. This means that you have to
be careful in sending/receiving datagrams. It means that even if some software has deficiencies, its still
important to make sure that you do not exploit its obscure protocols.
2. End-to-end Principle. This is one of those principles that continuously evolves. Overall intelligence
and state are important for maintaining this expression, and its also essential for network address
translators, firewalls, and in managing content caches, as well.
Now, in order to provide Java with its much-needed abstraction layers, Encapsulation is done. It is aligned
with the protocol suites functional division so that each level would be properly encapsulated and dealt
with.
Take a look at the diagram below for you to understand how the process works:
First HostRouter Router Second Host
Application Process to ProcessApplication
Transport Host to Host Transport
Internet Internet Internet Internet
Link Link Link Link
Ethernet Fiber Satellite Ethernet
Take note that whatever is on top of the layer are those that are closely used in the user applications
themselves. However, there is no single architectural model that has to be followed, especially when you
have less-defined models such as the OSI model. This is its main difference from other internet protocols,
especially the earlier ones. Encapsulation then covers the 4 Abstraction Layers which are as follows:
Abstraction Layers
Inheritance
Then, there's also inheritance that describes what each class would inherit or how they would relate to
their parent pages.
What you have to understand about Java is that it is an Open System Interconnect (OSI) Internet Model
which means that it works in inheritance (). In order to establish connections, you need to make use of
listening inheritance so that the host could make callsor in other words, connections.
By inputting listen (), the user will be able to accept () blocks on the program. This binds () the program
together and makes it whole. For this, you could keep the following in mind:
Client: socket()connectwrite()read() close()
Establish connections: connect accept()
Send Request: write() read()
Receive Reply: write() read()
Close Connection: close() read()
Server: socket()bind()listen()accept()read()write() read()
As you can see, youre able to connect one with the other because you have established the proper
inheritancealso known as rolesin your program.
Internet Model
Now, to make things clearer, you have to understand the basic model of the internet.
The Internet Model combines session, presentation, and application of layers and the ports of the Java,
making way of bind() to happen. Now, you also have to wait from the response from both the sender
and the receiver. This makes it easy for the exchange of requests and messages to be done until the
connection is closed. When done properly, the sender and receiver wont have to worry about messages
getting unsent, or communications getting cut.
Connections could then be contained in just one thread so that it would not be too complicated for the
network to understand. This way, the right Protocol Stacks could be created, too. Therefore, it would have
to be this way:
Patterns
Now, you also have to keep the following patterns in mind:
1. Java Stream. This is responsible for providing I/O mechanisms to the network and also provides peer
addresses, as well.
2. Java Acceptor. This allows passive acceptance of the Java mechanisms from a factory class all the
way to the client. It establishes connections to the client.
3. Java Connector. This allows mechanisms to connect to the socket so thered be a good relationship
between the servers.
Stream Class
To start programming, you could begin with the Stream Class. This provides the right data to be sent and
received by various methods involved in Java, and also contains proper socket descriptors and grants
privileges to others in the program. Some may even be deemed private, to make the experience better for
the users.
To code, you could follow whats written below:
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string>
using namespace std
class JavaStream
{
int m_sd;
string m_peerIP;
int m_peerPort;
public:
first class JavaAcceptor;
first class JavaConnector;
~JavaStream();
ssize_t send(char* buffer, size_t len);
ssize_t receive(char* buffer, size_t len);
string getPeerIP();
int getPeerPort();
private:
JavaStream(int sd, struct sockaddr_in* address);
JavaStream();
JavaStream(const JavaStream& stream);
};
Polymorphism
Basically, Java Polymorphism are the ones that define applications, and serve as containers for different
parts of the application. They also serve as containers for various application controllers, and they
always belong to Polymorphism.
In order to create a module, you have to make use of the Java.mobile function. Whats inside the
parenthesis would then determine the element where the application would run in, so that you could add
filters, directives, and controllers to the application. An example is shown below:
<div ng-app="FavoriteApp">...</div>
<script>
var app = Java.module("FavoriteApp", []);
</script>
Adding Directives
Now, you could add directives to improve the functionality of the app you are trying to create.
Directives are pretty much the terminologies given in Chapter 2, but could also be any of the following:
1. Validation Properties, such as: $error, $invalid, and $dirty.
2. Java.isDate. Returns value if date is the reference.
3. Java.isArray. Pertains to array values.
4. Java.isNumber. Pertains to numerical values.
5. Java.isFunction. Pertains to functional values.
6. Java.isElement. Pertains to DOM Elements.
7. Java.isDefined. Pertains to references that are defined.
8. Java.equals. Pertains to equal values on the program.
9. Java.isUndefined. Pertains to undefined reference values.
10. Java.isObject. Pertains to object references.
11. Java.forEach(). This helps elements execute various functions whether in arrays, or objects.
12. Java.Copy(). This gives you deep copies of arrays or objects.
13. Java.uppercase(). This changes values to uppercase letters
14. Java.lowercase(). This changes values to lowercase letters
15. <textarea>. Modifies the text areas behaviors.
16. <select>. Helps you create selections on the program.
17. <script>. This modifies the behaviors script.
18. <input>. This helps you input different functions to the program.
19. <form>. This helps you create forms in the program.
20. <a>. This one helps input various variables in the program.
21. Java.module(). This helps you create, retrieve, or register Polymorphism.
22. Java.element(). This makes use of JQuery Elements to wrap the HTML Element with.
23. Java.bootstrap(). This manually starts Java JS.
You could also use your own directives, which means the code would look something like the one
below:
<div ng-app="FavoriteApp" w3-test-directive></div>
<script>
var app = Java.module("FavoriteApp", []);
app.directive("w3TestDirective", function() {
return {
template : "I was made in a directive constructor!"
};
});
</script>
Adding Controllers
Of course, you could also add controllers to your codes by using the ng-controller directive. Basically, it
would show up like this:
<div ng-app="FavoriteApp" ng-controller="myCtrl">
{{ AppFirstName + " " + ApplastName }}
</div>
<script>
var app = Java.module("FavoriteApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "Harry";
$scope.lastName = "Styles";
});
</script>
<script>
var app = Java.module("FavoriteApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "Harry";
$scope.lastName = "Styles";
});
</script>
</body>
</html>
Filters
No, this has nothing to do with adding filters to your photos to spruce them up. Filters give your
applications more lifegive them some form of body and souland could allow you to code what you
want to happen to the app. This means you have to use the following variables:
1. uppercase. This helps you format a string to uppercase letters.
2. orderBy. This arranges the array based on the expressions used.
3. number. This helps format numbers into strings.
4. lowercase. This then formats the string into lowercase letters.
5. limitTo. This one limits strings or arrays into characters or elements that have been specified for them.
6. json. This helps format objects into JSON Strings.
7. filter. This helps you select subsets from arrays.
8. date. This helps format dates into formats that you have specified for them.
9. currency. This then helps you format currency numbers.
Expression Filters
The pipe character (|) is used to add expressions inside filters. For this, you could try the examples
below:
<div ng-app="myFavoriteApp" ng-controller="personCtrl">
</div>
<div ng-app="myFavoriteApp" ng-controller="personCtrl">
</div>
Currency Filters
Now, you could try transforming a number into currency by making use of currency filters, such as the
one you see below:
<div ng-app="myFavoriteApp" ng-controller="costCtrl">
</div>
Directive Filters
Of course, you could also tweak your directives by making use of directive filters. The ng-repeat
directive is essential here, as well as the pipe (|).
For example, if you want your variables to be in order, you should use orderBy, and code like this:
<div ng-app="myFavoriteApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | orderBy:'hogwartshouses'">
{{ x.name + ', ' + x.hogwartshouse }}
</li>
</ul>
</div>
Filter Filter
Wait, what?
Well, this is actually a thing! What happens here is that youre allowed to choose a subset from a certain
array, but you have to take note that you can only use what you have chosen for the same array. For
example:
<div ng-app="myFavoriteApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter : 'i'">
{{ x }}
</li>
</ul>
</div>
<p>Welcome to my Blog:</p>
<h1>{{Welcome to my Blog}}</h1>
</div>
<script>
var app = Java.module('myApp', []);
app.controller('myCtrl', function($scope, $java) {
$java.get("welcome.htm")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
To use the given methods above, you could code something that looks like the one below:
var app = Java.module('myApp', []);
app.controller('myCtrl', function($scope, $java) {
$java({
method : "GET",
url : "welcome.htm"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
There are also certain properties that have to be observed if you want to code HTTP or services. These
are the ones listed below:
1. .statusText. This is a string that defines the HTTP Status.
2. .status. This is a number that defines the HTTP Status.
3. .headers. This function is used to get information regarding the function.
4. .data. This is an object or string that carries server responses.
5. .config. This is used to generate requests from the objects you have onscreen.
To understand this better, you could check out the examples below:
var app = Java.module('myFavoriteApp', []);
app.controller('myCtrl', function($scope, $java) {
$java.get("welcometomyblog.htm")
.then(function(response) {
$scope.content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statustext;
});
});
var app = Java.module('myFavoriteApp', []);
app.controller('myCtrl', function($scope, $java) {
$java.get("wrongfilename.htm")
.then(function(response) {
//First function handles success
$scope.content = response.data;
}, function(response) {
//Second function handles error
$scope.content = "Something is wrong";
});
});
JSON Object
Meanwhile, the JSON Object is all about how you could transport data from JavaScript to Java, and
vice-versa. The ng-repeat directive should be looped for this function. For example, you want to import
data from a Blogspot blog to a WordPress one, it means that you are making use of a JSON Object.
You should also take note that $java.get() is all about reading the JSON Data, while $java() is mostly
about the XMLHttpRequestObject. Heres a good example:
<div ng-app="myFavoriteApp" ng-controller="studentsCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.Name + ', ' + x.house }}
</li>
</ul>
</div>
<script>
var app = Java.module('myApp', []);
app.controller('studentsCtrl', function($scope, $java) {
$java.get("students.php").then(function(response) {
$scope.myData = response.data.records;
});
});
</script>
Services
Its also important to use services because they allow certain functions to be limited only for your
application so other people would not go ahead and copy them, and have you dealing with copyright
claims.
There are a lot of services that Java offers, but the most important one is $location. This allows you to
save certain objects to the cloud and keep them safe, so that even if your computer or external drives
break down, you know your data would still be aroundwhich is important especially if youre dealing
with programs and applications. Here are some examples:
var app = Java.module('myFavoriteApp', []);
app.controller('studentsCtrl', function($scope, $location) {
myUrl = $location.absUrl();
});
You could also use the $timeout service or window.setTimeout to help you create countdownsthese are
mostly used for events, shows, and the like. For example:
var app = Java.module('myFavoriteApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hi People!";
$timeout(function () {
$scope.myHeader = "How are you doing today?";
}, 2016);
});
Meanwhile, the $java service could be used to obtain data coming from the server. Heres a good
example:
var app = Java.module('myFavoriteApp', []);
app.controller('myCtrl', function($scope, $java) {
$java.get("welcometomyblog.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
You could also try customizing your services by doing the following:
var app = Java.module('myFavoriteapp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hi everyone!";
$timeout(function () {
$scope.myHeader = "How are you doing today?";
}, 2000);
});
var app = Java.module('myFavoriteapp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1010);
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.filter('myFormat',['hexify', function(hexify) {
return function(x) {
return hexify.myFunc(x);
};
}]);
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(259);
});
Chapter 10 Conditional and Control Flow
Statements
Conditional Statements
You know how sometimes, you tend to want to edit you program and give it a more personal touch?
Well, Conditional Statements certainly help out with that.
The thing about conditional statements is that somehow, they give you the capacity to truly make the
program your own, and for that matter, here are some of those things that you can do to make the
program work the way you want it to.
Java Forms
Of course, there are also times when you need to add forms to your website or application so you could
get information from your subscribers, just to make sure that they are not spambots. For this, the
following input elements are used:
1. text area elements
2. button elements
3. select elements
4. input elements
You should also take note of the following:
1. Ng-click is used to invoke the reset () method directly but only when the user clicks the button.
2. The reset () method makes master and user objects equals.
3. The formCTRL controller is all about controlling the forms that you have on your application or
website.
4. The ng-model binds two user elements together.
5. The ng-app then defines the main Java application.
To make this clearer, you could try the example given below:
<div ng-app="myFavoriteApp" ng-controller="formCtrl">
<form novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" ng-model="user.lastName">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</div>
<script>
var app = Java.module('myFavoriteApp', []);
app.controller('formCtrl', function($scope) {
$scope.master = {firstName: "Harry", lastName: "Potter"};
$scope.reset = function() {
$scope.user = Java.copy($scope.master);
};
$scope.reset();
});
</script>
Now, if you want to create Select Boxes for your forms, you could do that by trying the example below.
These boxes are important because they allow people to choose what they want.
<form>
Select a topic:
<select ng-model="myVar">
<option value="">
<option value="stdnts">Students
<option value="cats">Cats
<option value="house">houses
</select>
</form>
Meanwhile, you could also put radio buttons by using the ng-model directive. This means that while
what people see onscreen could have different values, only the selected items would reflectmaking
whats going on in the app easier to understand. For example, if your select boxes are:
<form>
Select a topic:
<select ng-model="myVar">
<option value="">
<option value="stdnts">Students
<option value="cats">Cats
<option value="house">houses
</select>
</form>
Then it means that your values should be based on the variables below:
<form>
Pick a topic:
<input type="radio" ng-model="myVar" value="stdnts">Students
<input type="radio" ng-model="myVar" value="cats">cats
<input type="radio" ng-model="myVar" value="house">houses
</form>
As for checkboxes, it basically means that you want to know whether something has a value of true or
false. When you apply the ng-model directive, the value will then show up in the application that you are
using. In this case, you have to code like what you see below:
<form>
Check to show your favorite header:
<input type="checkbox" ng-model="myVar">
</form>
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.houses}}</td>
</tr>
</table>
</div>
<script>
var app = Java.module('myFavoriteApp', []);
app.controller('customersCtrl', function($scope, $java) {
$java.get("$Java://www.hogwartshouses.com/Java/customers.php")
.then(function (response) {$scope.names = response.data.records;});
});
</script>
To keep your information in order, you have to use the orderBy directive. A good example could be seen
below:
<table>
<tr ng-repeat="x in names | orderBy : 'house'">
<td>{{ x.Name }}</td>
<td>{{ x.house }}</td>
</tr>
</table>
You could also display CSS style elements on your table. To do it, you could try coding the elements
below:
<style>
table, th , td {
border: 1px purple;
border-collapse: collapse;
padding: 8px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
And finally, to customize it even more, you could change letters to uppercase, enter table index, and use
$odd and $even factors. Take a look at the examples below:
<table>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Name }}</td>
<td ng-if="$even">{{ x.Name }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.house }}</td>
<td ng-if="$even">{{ x.house }}</td>
</tr>
</table>
<table>
<tr ng-repeat="x in names">
<td>{{ $index + 1 }}</td>
<td>{{ x.Name }}</td>
<td>{{ x.house }}</td>
</tr>
</table>
<table>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.house| uppercase }}</td>
</tr>
</table>
int start();
JavaStream* accept();
private:
JavaAcceptor() {}
};
To destruct:
myJavaAcceptor::~JavaAcceptor()
{
if (m_lsd > 0) {
close(m_lsd);
To construct:
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include "Javaacceptor.h"
JavaAcceptor::JavaAcceptor(int port, const char* address)
: m_lsd(0), m_port(port), m_address(address), m_listening(false) {}
Comments
To create comments, just use hashtag (#)this really sounds like its social-media friendly, huh? For
example:
Example 1:
#!/usr/bin/java
# First comment
print "Hello, Java!" # second comment
[ etc. ]
Or
1 try:
2 do_some_stuff()
3 except:
4 rollback()
5 raise
6 else:
7 commit()
Or
1 try:
2 do_some_stuff()
3 finally:
4 cleanup_stuff()
To get useful exception information:
1 (a,b,c) = d
Java would then say:
1 ValueError: unpack list of wrong size
You may also try:
1 try:
2 a, b, c = d
3 except Exception, e:
4 e.args += (d,)
5 raise
Thats definitely easier than lengthy C programming exception handlers!
PDB Debuggers
As for removing bugs in the system, try the PDB Method firstthis is known as the easiest Java
Debugger!
>>> import pdb
>>> a="a string"
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) p a
'a string'
(Pdb)
You can continue the execution by typing cont in. You can also run this program automatically by typing:
# code snippet, to be included in 'sitecustomize.py'
import sys
sys.excepthook = info
Try these shortcuts, too:
# Ned's .pdbrc
# Print a dictionary, sorted. %1 is the dict, %2 is the prefix for the names.
alias p_ for k in sorted(%1.keys()): print "%s%-15s= %-80.80s" % ("%2",k,repr(%1[k]))
def main():
logging.basicConfig(level=logging_level, filename=options.logging_file,
format='%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
parser = optparse.OptionParser()
parser.add_option('-l', '--logging-level', help='Logging level')
parser.add_option('-f', '--logging-file', help='Logging file name')
(options, args) = parser.parse_args()
logging_level = LOGGING_LEVELS.get(options.logging_level, logging.NOTSET)
if __name__ == '__main__':
main()
Now, you would no longer have a hard time trying to correct those errors!
Conclusion
Thank you for reading this book!
Hopefully, this book has not just taught you about Java and its principles, but also how you can create a
program using this language, top.
Do try the techniques you have learned here, and see how it goes!
Finally, if you enjoyed this book, please take time to post a review on Amazon. It will be greatly
appreciated.
Thank you, and good luck!
Bonus: Preview Of SQL The Ultimate Beginners
Guide Learn SQL Today
For beginners, learning SQL is like learning how to speak a foreign language. You have to learn the
alphabets first before you can successfully use it. Knowing the definition and purposes of SQL is crucial,
before you, as a beginner can make any significant progress.
Looking at those symbols and queries may seem scary and confusing, but do not worry, the technical
jargon is explained in the simplest manner to facilitate your comprehension.
What is SQL?
SQL stands for Structured Query Language. It is a standard programming language used in fetching or
retrieving tables from databases. Other areas of use is creating, accessing and manipulating databases.
The most commonly used versions of the SQL are the SQL99 standard originally established by ANSI
(American National Standards Institute). There is also an ORACLE version called PL/SQL, and a
Microsoft version called T-SQL or Transact-SQL.
More people are growing aware of it because SQL is one of the easiest and most powerful methods of
editing databases. It works in such a way that you can perform your tasks more efficiently, within a shorter
timeframe.
The SQLs basis is the RDBMS (Relational Database Management System), which stores data in the form
of tables.
Thank you again for downloading this book!