Insurance experts at the
Consumer Federation of America say consumers need to be more aggressive
in ensuring they're getting the lowest possible price from their car
insurance company.
J. Robert Hunter, Director of Insurance at
CFA and former Texas Insurance Commissioner, says it's never been more
important to shop around for insurance. “You
may have been with your auto insurance company for many years. You may
even receive a loyalty discount of five or ten percent on your bill. You
have filed few or even no claims during your years with the insurer.
You are a great customer and it may seem that there’s no reason to
complain about your auto insurance," Hunter said, warning that it's just
such customers who are targeted by rate increases.
“Watch
out! Your insurer may be increasing your premium by far more than your
loyalty discount, precisely because you have been so loyal. Even if you
have a perfect driving record, many insurance companies are raising
rates on people just like you – people who do not shop around," he said.
"Newly revealed insurance practices show that reasons you might be
vulnerable to price increases are such things as staying with one
insurer for many years, never calling the company with complaints or
simply buying your insurance through an agent rather than online.”
Are you being PO-ed?
The name insurers use for such practice is “Price Optimization,” referred to as “PO.” The
industry uses personal consumer data and statistical models to measure
how likely each customer is to shop around and how much of a price
increase he or she will tolerate, Hunter said. After determining what
economists call the “price elasticity of demand,” insurers push up
premiums based on how unlikely it is that a customer will shop around
for a better price, even if the driver has never caused an accident or
been issued a ticket.
Many insurance companies, including
about half of the larger ones, raise a driver’s premium if they conclude
that the driver is not likely to leave their company, the CFA reported.
This means millions of drivers are possibly being charged a premium
that is higher than the amount considered appropriate and fair for their
risk profile.
What should a consumer do?
The best defense against being PO-ed is to shop around, according to Hunter. “Even
before the advent of price optimization it was very important to shop
for insurance since prices vary so widely. But now, to avoid being POed,
shopping is critical,” Hunter said. Hunter said consumers should also call their state’s Insurance Commissioner and tell her or him to stop insurance companies from using this Price Optimization scheme to unfairly raise rates on customers.
It's not just the purchase price of a car that determines whether
it's a good buy. Resale value also enters into the picture, and Subaru
and Lexus have taken top honors for best resale values in Kelley Blue
Book's annual survey of the mass and luxury markets.
Subaru
had three models taking the top spot while Lexus had six among a total
of 22 segments. Chevrolet and Toyota each have an impressive five models
winning 2015 Best Resale Value Awards, with the majority being trucks
or SUVs.
Kelley editors note that depreciation often is the
greatest expense incurred by drivers during the first five years of
vehicle ownership. An average 2015 model-year vehicle only will retain
about 38.2 percent of its original value after a five-year ownership
period, meaning that a $50,000 new car today will only be worth
somewhere close to $19,100 after five years.
Vehicles with average
or below-average resale values are plentiful and may be heavily
discounted while models with higher resale values may be a little more
expensive upfront and may not come with as many rebates and discounts,
which is why consumers need to carefully weigh the potential benefits of
a higher resale value down the road.
No surprises
This year's ratings were no big surprise.
"Lexus
notably captured the top luxury brand honors for the fourth year in a
row, and after previously winning the brand award in 2011, Subaru is
back on top again for 2015 as the best mainstream brand for resale value
across its entire lineup," said Eric Ibara, director of residual value
consulting for Kelley Blue Book.
"While both Subaru and Lexus
deliver incredible resale value, we also are impressed with the strides
made by General Motors, which tops domestic automakers with seven
combined awards for Chevrolet and GMC," Ibara said. "The entire list of
Top 10 Best Resale Value vehicles is dominated this year by trucks, SUVs
and crossovers, which is a testament to the strength these categories
will carry in the future."
COMPLETE RESULTS
2015 BEST RESALE VALUE: BRAND
SUBARU 2015 BEST RESALE VALUE: LUXURY BRAND
LEXUS
2015 BEST RESALE VALUE BY VEHICLE CATEGORY
SUBCOMPACT CAR: Honda Fit PLUG-IN VEHICLE: Porsche Cayenne S E-Hybrid COMPACT CAR: Subaru Impreza COMPACT SUV/CROSSOVER: Jeep Wrangler SPORTY COMPACT CAR: Subaru WRX MID-SIZE SUV/CROSSOVER: Jeep Wrangler Unlimited MID-SIZE CAR: Subaru Legacy FULL-SIZE SUV/CROSSOVER: Chevrolet Suburban FULL-SIZE CAR: Dodge Charger LUXURY COMPACT SUV/CROSSOVER: Mercedes-Benz GLK-Class ENTRY-LEVEL LUXURY CAR: Lexus RC 350 LUXURY MID-SIZE SUV/CROSSOVER: Lexus GX 460 LUXURY CAR: Lexus GS 350 LUXURY FULL-SIZE SUV/CROSSOVER: Lexus LX 570 HIGH-END LUXURY CAR: Lexus LS 460 HYBRID SUV/CROSSOVER: Lexus RX 450h SPORTS CAR: Chevrolet Camaro V6 MID-SIZE PICKUP TRUCK: Toyota Tacoma HIGH PERFORMANCE CAR: Chevrolet Corvette FULL-SIZE PICKUP TRUCK: Toyota Tundra HYBRID/ALTERNATIVE ENERGY CAR: Toyota Camry Hybrid MINIVAN/VAN: Toyota Sienna TOP 10 CARS
Chevrolet Colorado
Honda CR-V
Chevrolet Silverado
Jeep Wrangler
Ford F-150
Toyota Tacoma
GMC Canyon
Toyota Tundra
GMC Sierra
Toyota 4Runner
(Residual
values used for award calculations are based on the 2015 model-year
vehicles that appear in the January/February 2015 Kelley Blue Book®
Residual Value Guide. Top 10 models appear in alphabetical order).
The death of a Honda Accord owner highlights a major flaw in
the current safety recall system -- namely, the failure of car owners
and dealers to have recalls performed before selling a car.
According
to a lawsuit, Carlos Solis IV bought his 2002 Honda Accord in April
2014 from All Stars Auto Sales in Cypress, Texas, not knowing that the
previous owner had ignored several recall notices mailed in 2011.
On
Jan. 18, Solis was involved in what was described as a "relatively
minor" collision with a 2003 Infinit G35. When his airbag deployed,
shards of metal from the recalled Takata airbag allegedly struck Solis
in the neck, killing him, Automotive News reported.
More
than 8 million cars have been recalled in a massive effort to replace
airbags that may contain faulty inflators. At least five deaths have
been attributed to the airbags.
“Our
heartfelt condolences go out to the driver's family," Takata said in a
statement. "The incident cited involved a vehicle that had been
previously recalled, and we are working in close collaboration with
Honda to determine the facts and circumstances surrounding the vehicle's
status at the time of the incident. Takata's number one priority is the
safety of the driving public.”
The car had been recalled a second time
more recently, in June 2014, as the original Takata airbag recall was
expanded. But Honda said it had not notified Solis of that recall at the
time the accident happened.
Used car dealers are not required to
repair recalled vehicles and are not even required to inform consumers
that they are purchased a recalled car or truck.
The only way
consumers can check with their vehicle has any outstandint recalls is to
check an online database like the one maintained by the National Highway Traffic Safety Administration. Carfax also has easy-to-use recall search.
It's common for new car dealers to offer financing to their customers
but used cars dealers historically haven't been as involved in writing
loans, which a just-settled lawsuit suggests may be a good thing.
The
U.S. Justice Department and North Carolina's attorney general had
accused two of the state's used car dealers of discriminating against
minority consumers through their "Buy Here, Pay Here" plans.
The
dealers, Auto Fare Inc. and Southeastern Auto Corp., both of Charlotte,
have agreed to pay $225,000 and clean up their lending practices to
bring them into compliance with the Equal Credit Opportunity Act. The lawsuit charged the dealers had used “reverse
redlining” by intentionally targeting African-American customers for
unfair and predatory credit practices. The settlement came after the
court denied the dealerships’ motion to dismiss the case and agreed that
reverse redlining by an auto lender is illegal discrimination.
“It
is not only illegal, but also fundamentally wrong, to target borrowers
of color for predatory loans and exploit their need for a car to do
essential tasks such as getting to work,” said Acting Assistant Attorney
General Vanita Gupta of the Civil Rights Division. “I hope that other
buy here, pay here dealerships will evaluate their practices in light of
this settlement.”
“All
consumers deserve to be treated fairly when they buy a car,” said North
Carolina Attorney General Roy Cooper. “We hope this case sends a strong
message that car dealers cannot use race when targeting buyers with
overpriced cars and oppressive loans.”
Improved practices
The
settlement requires the dealerships to implement a number of specific
practices to ensure that the terms of their loans and repossession
practices are no longer unfair and predatory. The required changes
include:
limiting projected monthly payments to no more than 25% of a borrower’s income;
requiring interest rates to be at least five percentage points below the state’s rate cap;
mandating
a lower interest rate for borrowers who have specified evidence of
lower credit risk; requiring competitive sales prices;
prohibiting hidden fees on top of the required down payment;
prohibiting repossessions until at least two consecutive missed payments;
providing down payment refunds to borrowers who quickly go into default;
requiring strict compliance with provisions of state repossession law enacted to protected consumers;
providing
borrowers improved disclosures at the time of sale (including
disclosing the presence of any GPS, or automatic shut off, device);
allowing
borrowers to obtain an independent inspection of the car before
completing the purchase; and providing borrowers improved notices before
repossession.
The
settlement also requires defendants to establish a $225,000 settlement
fund to compensate victims of their past discriminatory and predatory
lending.
“Predatory lending practices that lock consumers
into contracts they cannot afford are illegal and can spell financial
disaster for borrowers of lower income or challenged credit history,”
said U.S. Attorney Anne M. Tompkins of the Western District of North
Carolina. “Today’s settlement ensures that all customers of Auto Fare
Inc. and Southeastern Auto Corp. will have equal access to credit
regardless of their race.”
The lawsuit alleged that the two
dealerships’ sales prices, down payments, and interest rates were
disproportionately high compared to other subprime used-car dealers.
Because the dealerships did not meaningfully assess the customers’
creditworthiness or ability to repay, their rates of default and
repossession were disproportionately high. Additionally, the
dealerships engaged in repossessions when customers were not in default. source: Car dealers'
When you shop for a new car, chances are you focus on the cost of the vehicle – what you have to pay to drive it off the lot.
But have you thought about what it will cost after that? The analysts at Kelley Blue Book (KBB) have, and have singled out 2 brands for the lowest projected cost of ownership over the first 5 years of a new car's life.
“New
car shoppers usually pay a lot of attention to how much a car will cost
upfront; however, sometimes an even more expensive car on the front end
can actually save you money during the first five years of ownership by
having low total ownership costs,” said Dan Ingle, vice president of
vehicle valuations for Kelley Blue Book. “Kelley Blue Book’s 5-Year Cost
to Own information evaluates the other out-of-pocket expenses drivers
will incur beyond the initial purchase price, which helps consumers
choose the vehicle that fits their needs and their long-term budget
best, helping save money down the road.”
Loss of value
Those
costs include depreciation, or loss of value. It's a truism in the auto
industry that a new car can lose thousands of dollars of value just by
being sold to a consumer. But some cars lose value faster than others.
There
are other costs that come with owning a car, such as expected fuel
costs, insurance premiums and expected maintenance and repair costs.
Based on all those potential costs, KBB selected Subaru as the top 2015 brand and Lincoln as the top luxury name plate.
KBB
analysts say Subaru stands out because of its low depreciation costs
and strong residual values among all its models. That means consumers
who keep their Subarus in top condition will enjoy strong trade-in value
when it comes time to sell. It should also be cheaper to lease a Subaru
since lease payments are calculated on the difference between the
purchase price and residual value.
Fair purchase price
In
addition, KBB found Subaru has a mid-range Fair Purchase Price and
competitive fuel costs, making it the 2015 5-Year best brand to own
among all carmakers. Some of the models giving Subaru the edge include
the 2015 Subaru Forester, Impreza, Legacy, WRX, Outback and BRZ.
Subaru
also recently drove away with the overall brand award in Kelley Blue
Book’s 2015 Best Resale Value Awards for having the best projected
resale value across its entire 2015 model-year lineup.
Among luxury name plates, Lincoln
takes the crown. KBB analysts singled it out for the lowest average
total maintenance costs of any luxury brand. It also ranks high when it
comes to holding resale value and for low insurance costs.
The Lincoln models getting the most praise are the 2015 Navigator, MKX and MKZ.
Best car for the money
KBB isn't the only automotive authority with an opinion in this area. U.S. News has released its survey of the 2015 automotive field, picking the Lexus RX 350 SUV for the seventh straight year as Best Car for the Money.
But
not everyone wants, or can afford, a luxury SUV so the magazine has
picked a single car as best in 21 categories. Among subcompacts, it
singled out the the 2015 Honda Fit. Among full-size models, the 2015 Chevrolet Impala took the prize.
Honda was the carmaker recording the most wins. Honda and its Acura brand won 3 awards each.
"In
recent years, Honda has focused on providing more standard features in
its Honda products and sportier performance for Acura models," said
Jamie Page Deaton, managing editor of U.S. News Best Cars. "That focus
has resulted in more praise from professional car critics.”
The
amount of coverage you need varies from state to state. If you are a
cautious person, you might opt for a more expensive policy with better
coverage. If you have a lot of assets, experts recommend that you get
enough liability coverage to protect them; otherwise the other party
involved in an accident could have attorneys go after your assets as
well.
Read the policy:
Carefully examine the insurance policy to understand exactly what is
covered and make the right adjustments to suit your unique situation.
Limits:
Pay attention to the limits set by the insurance policy. In some cases,
there will be a maximum payout, which may not be as high as you’re
looking for.
Are there exceptions?
Sometimes
policies will have exceptions and you’ll end up paying out of pocket
for an accident or repair that you thought would be covered.
Other driver’s don’t have insurance:
If you get into a collision with an uninsured driver, you’ll have to
pay for repairs out of your own pocket and sue for damages.
Car theft: Insurance policies don’t always cover car theft.
Damage from natural accidents: Some insurers don’t cover collisions with animals, tornados, earthquakes, damage from falling objects, etc.
Mechanics and replacement parts
Some
insurers will push you to use shops in a direct-repair program or use
cheaper replacement parts rather than the original equipment
manufacturer.
Are service providers reputable?:
Check the fine print of the policy to see if the insurer has control
over which service providers and parts are used for repairs.
Can you choose a service provider?: Choosing your own mechanic is the best case scenario, but they aren’t always covered by insurance policies.
What if the replacement part breaks?: Find out how the insurer handles faulty repairs and how quickly they will take care of it.
Cost
The cost of auto insurance is a big factor in most people’s decision about which policy to choose.
Premium: The premium is the monthly or yearly price that you pay for your insurance plan.
Deductible:
Deductibles are the amount of money you are required to pay before your
insurance company starts to pay out. The lower your deductible, the
higher your premium.
Coverage factors:
Depending on what level of coverage you opt for, the cost of your
insurance will vary. Your past driving record, credit rating and level
of coverage will all affect how much your policy costs.
Optional coverage
In addition to basic auto insurance, there are optional coverages available for drivers with different needs.
Collision coverage:
Collision coverage pays for the expenses to repair your car. If you
drive an older car that isn’t worth much money, it may not be worth it
to pay for collision insurance.
Comprehensive coverage:
This covers things that could happen to your car that might not be
covered by standard insurance, such as weather damage, running into an
animal or other factors. It’s a good idea to opt for comprehensive
coverage if you can afford it, but it can get costly so if you drive an
inexpensive car it’s probably not worth it.
Uninsured motorist protection:
This protects drivers in the event that they get into an accident with a
person who isn’t insured but is to blame for the accident. It will
cover damages to the car and injury in the event that another driver is
unable to pay out.
Insurance company ratings
An
insurance company’s reputation is important. Good companies should have
a quick response time, be adept at handling claims and have excellent
customer service.
Reviews and complaints:
Check the reviews and ratings on an insurance company before purchasing
a policy. Be aware of any complaints that have been filed.
Handling claims:
How long does it take for the company to handle a claim? Do you have to
pay out of pocket first or do they cover the expenses immediately?
What are different types of auto insurance policies?
Liability insurance
Liability
insurance covers you if you’re in an accident and the accident is
deemed to be your fault. It will cover repairs to damaged property as
well as medical bills resulting from injury. Most states require at
least a minimum amount of liability insurance but it’s a good idea to
purchase extra protection.
Collision coverage
If
you are involved in an accident, collision coverage will pay for the
repairs to your car. If your car is damaged beyond repair, good
collision coverage will pay for the value of your car.
Comprehensive coverage
If
something happens to your car that isn’t a straightforward accident,
such as weather damage, hitting an animal or theft, comprehensive
coverage will pay for the damage to the car.
Personal injury protection
Personal
injury protection is imperative for all drivers. Medical bills
following an accident can be devastating and good personal injury
coverage will cover medical expenses as well as missed work expenses.
Uninsured motorist protection
About
one in six drivers is uninsured, even though it is illegal to be.
Uninsured Motorist Protection offers payment when you are in a collision
with another driver who is at fault and does not have insurance. It is
usually relatively inexpensive to add uninsured motorist protection to a
car insurance policy.
Who's it for?
Drivers who own a car
Auto
Insurance is required by law for drivers in most states. Drivers who
own a car and drive it often should definitely have auto insurance to
cover the cost of damages to their car and personal injury. Otherwise,
repairs and medical costs can be very expensive.
Drivers who occasionally drive cars not their own
If
you don’t own a car but occasionally drive rental cars or cars that
belong to other people, you should still have auto insurance. The car
owner’s insurance typically doesn’t cover other drivers unless that is
stipulated in the policy.
Car owners who have other people drive their car
If
you own a car that other people drive, such as a hired car, you should
have auto insurance that covers the additional driver as he or she may
not have insurance.
Our goal in this series is to learn about Android SDK development. So far we explored the development tools, looked at the structure of an Android app project, started to create a user interface, and responded to user interaction. In this tutorial, we will look at the basic structures and concepts in Java that you need to know in order to start developing apps for Android.
Introduction
If you are already familiar with Java you can ignore this section. If you have limited or no familiarity with the language, then this tutorial will indicate what you need to learn in order to go any further with Android. This tutorial is not enough in itself to teach you Java from scratch, but will act as a primer to get you started. You should follow the tutorial with additional Java learning as necessary. We won't spend too long going over the details in this tutorial, but if you are struggling with any of the concepts check out the Oracle Java Tutorials. This is an extensive guide to the language that is accessible to beginners. Don't be too alarmed if you feel a little overwhelmed by what we cover in this tutorial at first, it will make a lot more sense once you start implementing the structures in Android projects.
1. Java Syntax
Step 1
You already saw a little Java syntax in our Android project, but for clarity, let's start another project. Rather than an Android project, this time we will use a Java one, so that you can easily see the structures we use. Open Eclipse. Click the "New" button. In the wizard that appears, scroll down to the Java folder and expand it. Select "Java Project" and click "Next". Enter "MyJavaProject" as the project name and click "Finish". Eclipse then creates your new project in the workspace. In the Package Explorer, expand the new project folder. Right-click on "src" and select "New" then "Class". Enter "MyMainClass" in the Name field. Check the checkbox with "public static void main" next to it and click "Finish". Eclipse creates your class and opens it in the editor. Don't pay much attention to the structure of the project or the existing content of the class because your Android projects will be differently structured. You can use this project to work on your Java coding skills, it's easier to run and test the code you write here than with an Android app, and you can focus on the Java syntax. The "public static void main" line you see in the class file is the main method. Whatever is inside this method executes when the application runs. The content of the method is what appears between the curly brackets after "public static void main(String[] args)". Eclipse may have generated a "to do" line - just ignore it. Create a new line after it and we will add our code there.
Step 2
In Java, a variable can store a data value such as a text string or number. When you create, or "declare" a variable in Java, you have to specify the type of the data within it and give it a name. Enter the following:
intmyNum;
This line declares an integer variable. We can declare a variable and assign a value to it by extending the line:
intmyNum = 5;
We can now refer to this variable using its name. Add the following line next, writing the variable value to the output console:
System.out.println(myNum);
You will not typically write to the system output like this in your Android apps, but will use the LogCat view instead. However, writing to the output in this way is a convenient way to test your Java code.
Step 3
Let's run the application. The process is slightly different for Android apps, but we'll get to that later in the series. Select "Run" then "Run Configurations". Select "Java Application" in the list on the left and click the "New launch configuration" button above it. Eclipse automatically selects your new Java application if it is the only one you have. Otherwise, select it using the "Browse" button. Click "Run" to run your application. You should see the number five written out to the Console view beneath the editor. You can use this technique to test your Java code as you learn it. You can run the project you ran last at any time using the "Run" button in the toolbar.
Step 4
You'll use the same syntax whenever you declare a variable in Java. To assign a different value to the variable later in the program, you can refer to it by name:
myNum = 3;
This overwrites the existing value. In Java there are many different variable types. The int is referred to as a primitive type, along with a few other number types, char for character values and boolean, which stores either a true or false value. There are also Object types; we will explore Objects later. An essential Object type to familiarize yourself with is String, which stores a text string:
String myName = "Sue";
Text string values are enclosed in quotes. You can include these directly in some cases, for example:
System.out.println("number: "+ myNum);
Add this code and run it, the console will display: "number: " followed by the variable value.
Step 5
Above we saw the assignment operator "=" - here are a few of the other common operators:
//add
myNum = 5+6;
//subtract
myNum = 7-3;
//multiply
myNum = 3*2;
//divide
myNum = 10/5;
//remainder
myNum = 10%6;
//increment (add one)
myNum++;
//decrement (subtract one)
myNum--;
The operators can be used on variables as well as hard-coded numbers (as above):
intmyNum = 5;
intmyOtherNum = 4;
inttotal = myNum+myOtherNum;//9
Step 6
One other Java structure that is essential to Android is the comment. You can add a comment in two ways:
//this is a single line comment
/* This is a multiline comment
* stretching across lines
* to give more information
*/
It is vital to get into the habit of commenting your code as you write it, for your own benefit as well as anyone else who reads the code.
2. Control Structures
Step 1
The code we added to the main method executes when the Java application runs. When the Android application we created runs, whatever is in the onCreate method of the main Activity is what runs. Each line inside these methods is executed after the previous line, but the flow of execution is not always linear. There are many control structures involved in Java, so let's look at some of the most common, starting with conditionals. Conditional statements involve carrying out tests to determine the flow of execution. The simplest conditional structure in Java is the if statement:
if(myNum>3)
System.out.println("number is greater than 3");
This tests determines whether the value of the variable is greater than three. If it is, the string will be written to output. If not, then nothing will be written out and processing simply moves to the next line in the program. We say that a conditional test "returns" a true or false value. True and false are boolean values. We can add an else, which only executes if the if returned false:
if(myNum>3)
System.out.println("number is greater than 3");
else
System.out.println("number is not greater than 3");
The else executes if the value is three or less. Try the code with different values for the integer variable to see the results of the conditional tests. We can also chain multiple tests:
if(myNum>10)
System.out.println("number is greater than 10");
elseif(myNum>7)
System.out.println("number is greater than 7");
elseif(myNum>3)
System.out.println("number is greater than 3");
else
System.out.println("number is 3 or less");
Each test performs only if all previous tests in the chain returned false. So for any number, only one string is output. You can chain as many else if statements together as you need. You can also use if statements chained with one or more else if blocks without a final else. We tested for one number being greater than another. Try the following variations:
if(myNum<10)
System.out.println("number less than 10");
if(myNum==10)
System.out.println("number equals 10");
if(myNum!=10)
System.out.println("number is not equal to 10");
if(myNum>=10)
System.out.println("number either greater than or equal to 10");
if(myNum<=10)
System.out.println("number either less than or equal to 10");
You can carry out similar tests on other variable types including strings. To carry out multiple tests at once, use the following syntax:
if(myNum>=10&& myNum<=50)
System.out.println("number is between 10 and 50");
The "&&", known as the "and" operator, means that the whole statement will only return true if both tests return true. The "or" operator will return true if either test returns true:
if(myNum<0|| myNum!=-1)
System.out.println("number is less than 0 or not equal to -1");
To group code into a block, we can use curly brackets - all of the code between the brackets executes if this test returns true:
if(myNum<10)
{
System.out.println("number less than 10");
myNum=10;
}
Such brackets group code in loops, methods, and classes.
Step 2
Let's look at loops now. The following for loop iterates ten times, meaning its content executes ten times:
for(inti=0; i<10; i++){
System.out.println(i);
}
The first expression in the for outline initializes a counter integer variable to zero. The second expression is a conditional test, checking that the variable is less than ten. If this returns true, the content of the loop executes, if not the loop will end. Once the content of the loop has executed, the third expression executes, incrementing the counter. The while loop uses slightly different syntax. The following example has the same effect as the for loop:
inti=0;
while(i<10){
System.out.println(i);
i++;
}
Loops can contain multiple lines of code, including other loops.
Step 3
We have already encountered the main method and the Android onCreate method. Let's look at creating your own methods. Place the following method after the closing bracket for your main method:
publicstaticvoiddoSomething(){
System.out.println("something");
}
This method is defined as public, meaning any class in the project can call on its processing. If it was "private" it's only accessible inside the class (this is "visibility"). You will not typically have to include the "static" modifier in your first Android apps, so ignore it. The "void" represents the return type. In this case the method returns nothing. To execute the method, add a call to it back in your main method:
doSomething();
Run your application to see this function. Alter the method to return a value:
publicstaticintdoSomething(){
return5;
}
Alter the method call and run again:
System.out.println(doSomething());
The returned value is written out. Methods can also receive parameters:
When calling the method, you must pass parameters of the correct type and number:
System.out.println(doSomething(3, 5));
Methods can split application processing into logical chunks. They are particularly useful if you need to carry out the same tasks more than once; you simply define them in the method then call it whenever you need it. If you change the process, you only need to change it in the method code.
3. Classes and Objects
Step 1
We've seen how methods can be used to reuse code and to split it into logical sections. Classes and objects do this on a larger scale. You can divide the tasks in an application up between objects, with each object having a set of responsibilities defined by its class. This is similar to a method being responsible for a particular area of functionality, but an object can have multiple methods and also store data values. Imagine you are creating a game - you can create a class dedicated to handling the details of the user. Select your application package, in "src", in the Package Explorer. Right-click and choose "New" then "Class". Enter "GameUser" as the class name, make sure the main method stub checkbox is unchecked this time and click "Finish". Eclipse then opens the class file, which initially only has the class declaration outline in it:
publicclassGameUser {
//class content
}
Everything you add is between these brackets (unless you add import statements, which are listed above this section). Your Android apps notice that the class files lists the package name at the top. It isn't listed here because we used the default package.
Step 2
Inside the class, add a couple of variables:
privateString playerName;
privateintscore;
These are called "instance variables" because they are defined for each instance of the class we create. Add a constructor method after these. This is what executes when an object of the class is created:
publicGameUser(String userName, intuserScore){
playerName=userName;
score=userScore;
}
The constructor always has the same name as the class and may or may not require parameters. The constructor should typically assign values to the instance variables, often using the parameters.
Step 3
The class can also define methods. Add the following typical set after the constructor:
These are known as get and set methods, or getters and setters, because they provide code external to the class with the ability to retrieve and set the values of the instance variables. Have a look at the Outline view in Eclipse to see how it can help to navigate class content.
Step 4
Save your new class file. Back in your main class, create an object of the new class in the main method:
GameUser aUser = newGameUser("Jim", 0);
We pass the parameters listed in the constructor - the "new" keyword will make the constructor execute. We can now use this instance of the class to access the data values in it by calling its methods:
System.out.println(aUser.getScore());
aUser.setScore(5);
System.out.println(aUser.getScore());
Run the program to see how the value changes after calling the public methods on the object. You can create multiple instances of the object which will be managed separately:
GameUser anotherUser = newGameUser("Jane", 5);
4. Inheritance & Interfaces
Step 1
We've seen how a class defines the sets of responsibilities you can make use of by creating object instances. This applies not only to classes you create yourself, but also to existing Java and Android classes which you can also make use of. As well as creating instances of these platform classes, you can extend them using inheritance. With inheritance, you can create a class which inherits the functionality of an existing class while also providing its own processing. We saw an example of this in the first Android project we created, with the main Activity class. Open the class now. In the opening line of the class declaration you will see "extends Activity". This means that the class is a subclass of the Android Activity class. Using the Activity class lets Android handle the details of presenting a screen to the user, with methods for when the screen is in various states (created, paused, destroyed, etc). This lets you focus on the unique aspects of the app, by adding code to the methods defined within the Android Activity class declaration and additional methods of your own if necessary. This is a pattern you will often use on Android, extending defined classes for common aspects of apps. You can complement these with your own classes where appropriate.
Step 2
Look again at your Activity class opening line. Remember that we added "implements OnClickListener" to handle clicks on a button in the UI. This is referred to as implementing an Interface. An Interface is similar to a class you inherit from using "extends" except that the Interface declaration simply lists method outlines. You have to provide the method implementation for each of them. So when we implemented OnClickListener we committed the class to providing an onClick method, which we did. An Interface is therefore like a contract. With inheritance, extending classes inherits the method implementations provided in the class declaration for their superclass (the class being extended). You can override these implementations if you need to.
Conclusion
In this tutorial we outlined some of the essential features of Java syntax you need to understand. There are more structures and concepts to become familiar with. If you don't have Java experience and want to make sure you know enough to develop effectively for Android, use the Oracle Java Tutorials. Topics to consider learning about include arrays and switch statements. Later in the series we will look at some of the most common Android classes you are likely to use. In the next part, we will explore the resources in an Android app project.