In this tutorial you will learn more Java and will look at Java loops and operators. This will allow you to write a simple Java app that you can then use in your IDE
About this Tutorial –
Objectives –
This course is aimed at object-oriented developers (e.g. C++ or C#) who need to transition into Java. It is also aimed at those learning to program for the first time; the course covers the Java programming constructs and APIs quickly, focussing on the differences between Java and other OO languages.
Audience
This training course is aimed at OO developers who need to transition into Java.
Prerequisites
No previous experience in Java programming is required. But any experience you do have in programming will help. Also no experience in eclipse is required. But again any experience you do have with programming development environments will be a valuable.
Experience using a contemporary OO language such as C++ or C# would be useful but is not required.
Contents
The Java course cover these topics and more:
Flow Control: Decision making: if and if-else; The switch statement; Looping: for loops; while loops; do-while loops; for-each style loops; Assertionsv
Concurrency: Overview of multithreading; Creating new threads; Object locking; Using wait, notify, and notifyAll
Collections: Overview of Java SE collection classes; Generics; Using List-based collection classes; Using Set-based collection classes; Using Map-based collection classes; Collection techniques
Exam Preparation
The Java course will help you prepare for these certifications:
Example: // Use *= compound operator:
x *= a + b;
// Equivalent to the following (note the precedence):
x = x * (a + b);
Aside: Working with Strings
String concatenation
strResult = str1 + str2
strResult = str1 + obj
String concatenation
str1 += str2
str1 += obj
Examples
What do the following statements do? String message = "Hello";
int a = 5;
int b = 6;
System.out.println(message + a + b);
System.out.println(message + (a + b));
System.out.println("" + a + b);
System.out.println(a + b);
Casting
Implicit conversions:
Java implicitly converts less-precise expns to more-precise expns
byte -> short -> int -> long -> float -> double
Explicit conversions (aka casting):
You can explicitly cast an expression into a compatible other type
(type) expression
Might result in a loss of precision
Aside: Working with Bytes
You can assign an integer literal value to a byte
Compiler implicitly casts integer literal value into a byte byte age = 21;
// Equivalent to:
// byte age = (byte) 21;
If you do any arithmetic with bytes, the result is an int
Consider the following example: byte myAge = 21;
byte yourAge = 22;
int totalAge1 = myAge + yourAge; // This works.
byte totalAge2 = myAge + yourAge; // This doesn't work.
byte totalAge3 = (byte)(myAge + yourAge); // This works.
Relational Operators
There are 6 relational operators (all return boolean):
>> (signed right-shift, i.e. shift bits right and preserve top bit)
>>> (unsigned right-shift, i.e. shift bits right and set top bit to 0)
Order of Precedence
Operators have the following precedence (use parens to override this precedence):
Unary: ++ — + – ! ~ (type)
Multiplicative: * / %
Additive: + –
Bitwise shift: << >> >>>
Relational: > >= < <= instanceof
Equality: == !=
Bitwise AND: &
Etc…
Lab
Using operators
In the student project, write code to manipulate day, month, and year values using operators.
Suggestions and requirements:
To start off with, declare 3 integers with hard-coded values for the day, month, and year. // Declare 3 variables, for a hard-coded date.
int day = 3, month = 12, year = 2014;
Use a conditional operator (?:) to determine if it’s a leap year. A leap year is: (evenly divisible by 4 AND NOT evenly divisible by 100) OR (evenly divisible by 400); Use the remainder operator (%) to help you out here. // Is the date a leap year?
boolean isLeapYear = ((year % 4 == 0) && !(year % 100 == 0)) ||
(year % 400 == 0);
Test whether your “is-leap-year” algorithm works for various years. System.out.printf("Is %d a leap year? %s\n", year, isLeapYear ? "yes" : "no");
if-else-if tests – Executes body1 if booleanTest1 is true, Or executes body2 if booleanTest2 is true, Or executes body3 if booleanTest3 is true, If all else fails, executes (optional) lastBody. if (booleanTest1) {
body1
}
else if (booleanTest2) {
body2
}
else if (test3) {
body3
}
...
else {
lastBody
}
Validate the day, month, and year values. Output a single message saying whether the date is valid or not. If the date is valid, output it in the format dd/mm/yyyy
Suggestions and requirements:
Write an if-statement to validate the month (it must be 1 – 12). // Is the date valid?
boolean isValid;
Write an if-statement to validate the year (for the sake of argument, let’s say the year must be 0 – 2099). } else if (year < 0 || year > 2099) {
isValid = false;
Write a switch-statement to ensure the day isn't too big. The maximum value is 28, 29, 30, or 31, depending on the month (and if the month is February, whether it's a leap year). } else {
int maxDay;
switch (month) {
case 2:
maxDay = (isLeapYear) ? 29 : 28;
break;
case 4:
case 6:
case 9:
case 11:
maxDay = 30;
break;
Refactor your application so that it gets a series of dates from the user, rather than having a single hard-coded date.
Suggestions and requirements:
Write a do-while loop that allows the user to enter a series of different dates. Each time round the loop, ask the user whether he/she wants to continue; if the user says "Yes" or "yes", keep on iterating. do {
// Ask the user whether he/she wants to enter another date.
System.out.print("\nEnter another date? ");
response = scanner.next();
} while (response.toUpperCase().equals("YES"));
Inside the loop, ask the user to enter a new day, month, and year. Use the Scanner class to help you here (see chapter 2 for a reminder of Scanner). // Get a date from the user.
System.out.print("Day: ");
day = scanner.nextInt();
System.out.print("Month: ");
month = scanner.nextInt();
System.out.print("Year: ");
year = scanner.nextInt();
If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Manage cookie consent
You can view this website without consenting to extra cookies. However you will need to accept the 'marketing' cookies to send messages via the contact forms & see any maps displayed on the site
Functional
Always active
Cookies necessary for the website to work.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.Cookies used to track user interaction on the site, which helps us to evaluate & improve the website.
Marketing: Forms & additional content (Marketing)
We need your permission to place ‘marketing’ cookies, so you are able to use the contact forms & see embedded content e.g. videos and maps. - - - - We have added protection to our contact forms to help prove that a human (rather than a spambot) is filling
If you would like to see more content like this in the future, please fill-in our quick survey.