In this tutorial you will learn more Java and will look at classes and variables. 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:
- Oracle Certified Java Associate – Exam 1Z0-803
- Oracle Certified Java Professional – Exam 1Z0-804
Overview
Estimated Time – 2 Hours
Not what you are looking? Try the next tutorial – Operators and Flow Control
Lab 1: Basic syntax rules
- Statements and Expressions
- Java code comprises statements
- Java statements end with a semi-colon
- You can group related statements into a block, by using {}
- Java code is free-format
- But you should use indentation to indicate logical structure
- Eclipse has a code-reformatting option (Ctrl+Shift+F)
- An expression is part of a statement. For example:
- a+b
- a == b
- Java code comprises statements
- Comments
- Single-line comment
- Use //
- Remainder of line is a comment
- Block comment
- Use /* */
- Useful for larger comments, e.g. at the start of an algorithm
- JavaDoc comments
- Single-line comment
- Legal Identifiers
- Naming Conventions
- Class names (nouns)
- Should start with uppercase letter
- Use “camelCase” letters/digits thereafter
- E.g. Person, AccountsDepartment, String, Console
- Interface names (adjectives)
- Same approach as for class names
- E.g. Runnable, Comparable
- Method names (verbs)
- Should start with lowercase letter
- Use “camelCase” letters/digits thereafter
- E.g. calculateInterest(), displayErrorMessage()
- Variable names (nouns)
- Should start with lowercase letter
- Use “camelCase” letters/digits thereafter
- E.g. total, numErrors
- Constant names (nouns)
- Should be all-uppercase
- Use underscores to separate
- E.g. SALES_TAX_RATE, MAX_RETRIES, BEST_TEAM_IN_WALES
- Class names (nouns)
Lab 2: Defining classes
- Class Declarations
- You can only declare one public class per file
- The file name must be className.java
- You can also define non-public classes in the same file
- Useful for classes that are only used locally
- More on this later
public class MySecondApp {
public static void main(String[] args) {
System.out.println("Eclipse says Hello");
}
}
class AnotherClass {
...
}
- When you compile this file, you get 2 class files:
- MySecondApp.class
- AnotherClass.class
- You can only declare one public class per file
- Class Visibility
- If you qualify a class as public
- The class is accessible by any other classes in the application
- If you don’t qualify a class as public
- The class is only accessible by classes in the same package
- Note:
- You can’t use private or protected on a class declaration
- If you qualify a class as public
- The main() Method
- Creating a project and adding a main class
- Open Eclipse
- Create a New Java project called StudentJavaLang
- In StudentJavaLang create a new package called student.javalang
- In the student.javalang package, create a new Java class named Main
- In the Main class, write a simple main() method to act as the entry-point for your application
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
- View code file.
- Run the application as it stands, to make sure everything is OK so far
Lab 3: Defining and using packages
- Overview
- A package is a group of related classes (and/or interfaces)
- Helps you organize the classes/interfaces in your application
- A package also corresponds to a physical folder on your computer
- When you compile a Java class, the .class file must be located on a folder named after the package name
- IDEs do this automatically e.g. see the bin folder in an Eclipse project
- Package names can include dots
- Represents a hierarchical folder structure
- E.g. a package name of com.osl.hr would correspond to a folder structure of com\osl\hr
- A package is a group of related classes (and/or interfaces)
- Defining a Package
- To specify a package, use the package keyword
- Must appear at the top of your Java source file (can be preceded by comments)
package mypackage;
// Remainder of code goes here ...
- Must appear at the top of your Java source file (can be preceded by comments)
- To specify a package, use the package keyword
- Importing Classes
- If you want to use a class that’s defined in a different package, you have 2 choices:
- Use the fully-qualified class name (i.e. package name plus class name) everywhere
anotherPackage.AnotherClass obj = new anotherPackage.AnotherClass();
- Import class(es) via import statements (located directly after the package statement)
package mypackage;
import anotherPackage.AnotherClass1; // Allows direct access to AnotherClass1.
import anotherPackage.AnotherClass2; // Allows direct access to AnotherClass2.
import anotherPackage.AnotherClass3; // Allows direct access to AnotherClass3.
// Or:
// import anotherPackage.*; // Allows direct access to any class in anotherPackage
- Use the fully-qualified class name (i.e. package name plus class name) everywhere
- If you want to use a class that’s defined in a different package, you have 2 choices:
- Standard Java Packages
- Java has hundreds of predefined packages
- Contain standard Java classes, grouped by functionality
- Named java.something or javax.something
- Some examples:
- java.sql Essential classes (e.g. String), auto-imported
- java.io Input/output classes, streams, file-related classes
- java.util Utility classes (e.g. Date, Scanner, collections)
- javax.swing Swing UI classes (for Windows-based apps)
- Java has hundreds of predefined packages
Lab 4: Declaring and using variables
- Variables
- All applications use variables
- A variable has a name, a type, and a value
- General Syntax
type variableName = initialValue;
- Example
int yearsToRetirement = 20;
- A variable also has a scope:
- Block scope
- Method scope
- Object scope
- Class scope
- All applications use variables
- Constants
- A constant is a fixed “variable“
- Use the final keyword in the declaration
- You can only assign a value once
- The compiler will ensure you don’t reassign a different value
- You can initialize a constant in a declaration:
final type CONSTANT_NAME = initialValue;
- Example:
final String ERROR_MESSAGE = "Incorrect input, please try again";
- A constant is a fixed “variable“
- Primitive Types
- Java has 8 primitive types
- Passed-by-value into methods
- The 8 primitive types are:
- byte 1-byte whole number, -128 to 127
- short 2-byte whole number, -32,768 to 32,767
- int 4-byte whole number, -2,147,483,648 to 2,147,483,647
- long 8-byte whole number, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
- float 4-byte floating-point number, -3.4E38 to 3.4E38, 7 sig figs
- double 8-byte floating-point number, -1.7E308 to 1.7E308, 16 sig figs
- char 2-byte (i.e. Unicode) character
- boolean Must be true/false (e.g. can’t use 1/0)
- Note:
- You’ll get a compiler error if you try to assign an out-of-range literal value to a variable
- Java has 8 primitive types
- Primitive Type Values
- Integer literals (decimal format):
- 10, -10 Integers
- 10L, -10L Long integers
- Integer literals (non-decimal formats):
- 0123, 0123L Octal (0..7)
- 0xFF56, 0xFF56L Hexadecimal (0..9a..f, uppercase or lowercase)
- Floating point literals:
- 3.5, -3.5 Doubles (optional D suffix)
- 3.5F, -3.5F Floats
- 3.5E9, 3.5E-9F Exponential syntax
- Character literals:
- ‘A’, ‘7’, ‘@’ Specific characters
- ‘\n’, ‘\t’, ‘\b’, ‘\\’ Escape sequences
- 97, ‘\u004F’ Character value (integer or Unicode notation)
- Integer literals (decimal format):
- Number Literals in Java SE7
- In Java SE 7, the integral types can also be expressed using the binary number system
- Add the prefix 0b or 0B to the number
byte aByte = (byte) 0b00100001;
short aShort = (short) 0b1010000101000101;
int anInt1 = 0b10100001010001011010000101000101;
- Add the prefix 0b or 0B to the number
- In Java SE 7, you can use underscores in number literals
- You can put _ anywhere you like
- Except at the start or the end of the number
long salary = 123_456_789;
- In Java SE 7, the integral types can also be expressed using the binary number system
- Reference Types
- Apart from the 8 primitive types, everything else is a reference type
- Passed-by-reference into methods
- The following are all predefined reference types
- All classes, e.g. String, Console, File
- All interfaces, e.g. Serializable, Runnable
- You can also define new reference types
- Apart from the 8 primitive types, everything else is a reference type
- Using Objects
- Create an instance (object) of the class
- Always allocated on the garbage-collected heap
classType objectRef = new ClassType(initializationParams);
- Always allocated on the garbage-collected heap
- Invoke methods on the object:
returnValue = objectRef.methodName(params);
- Optionally, when you’ve finished using an object, set the object reference to null
- If this is the last remaining reference to the object, the object is available for garbage collection
- The garbage collector is a background thread in the JVM, which periodically reclaims memory from unused objects
classType objectRef = new ClassType(initializationParams);
- Example of using objects
- Using the java.io.File class
import java.io.*;
...
public class DemoVariables {
...
public static void demoUsingClasses() {
File f = new File("C:\\eclipse\\notice.html");
long len = f.length();
System.out.println("File is " + len + " bytes long.");
}
...
}
- View code file.
- Using the java.io.File class
- Create an instance (object) of the class
- Local Variables
- A local variable is defined inside a method
- Local variables do not have a default initial value
- You must assign a value before usage (or compiler error)
- Note, for reference types, it’s OK to test for null
- Local variables can be declared final
- Means it can’t be reassigned thereafter
- Instance Variables and Class Variables
- An instance variable is defined outside of any method
- Accessible by any method in the class
- Represents data you want to preserve for entire lifetime of object
- Default initial value is zero-based (or null for reference types), so you don’t have to initialize before usage
- Can have an access modifier (e.g. private)
- A class variable (static) belongs to the class as a whole
- Shared between all instances of the class
- Permanently allocated
- An instance variable is defined outside of any method
- Declaring and using variables
- In the main() method, add code to do the following:
- Ask the user to enter an employee’s name, plus their salary (use the Scanner class to help you get the user’s input)
// Create a Scanner object to read from the "standard input" device.
Scanner scanner = new Scanner(System.in);
// Ask the user for details of first employee.
System.out.print("Enter the name of the first employee: ");
String name1 = scanner.nextLine();
System.out.print("What is the salary of " + name1 + "? ");
double salary1 = scanner.nextDouble();
// Skip over a trailing \n in input buffer.
if (scanner.hasNextLine()) {
scanner.nextLine();
}
- View code file.
- Output the details by using System.out.println()
// Output details for first employee.
System.out.println("Employee " + name1 + " earns " + salary1);
- Ask the user to enter an employee’s name, plus their salary (use the Scanner class to help you get the user’s input)
- Run the application to verify it all works. Then add more code as follows:
- Ask the user to enter the name and employee for another employee
// Ask the user for details of second employee.
System.out.print("\nEnter the name of the second employee: ");
String name2 = scanner.nextLine();
System.out.print("What is the salary of " + name2 + "? ");
double salary2 = scanner.nextDouble();
- View code file.
- Output these details
// Output details for second employee.
System.out.println("Employee " + name2 + " earns " + salary2);
- Also output the average salary
// Calculate and print the average salary.
double averageSalary = (salary1 + salary2) / 2;
System.out.println("\nAverage salary: " + averageSalary);
- Ask the user to enter the name and employee for another employee
- In the main() method, add code to do the following:
Lab 5: Useful Java classes
- Scanner
- The Scanner class is a handy way to scan (i.e. read) input from a stream
- Located in the java.util package
- You create a Scanner object to read input from a stream (e.g. System.in, or a file stream)
- You can then invoke methods to read input from that stream, e.g. next(), nextInt(), nextDouble()
import java.util.Scanner; // Gives us easy access to the Scanner class.
...
public static void demoScanner() {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
int i = scanner.nextInt();
double d = scanner.nextDouble();
...
}
- View code file.
- The Scanner class is a handy way to scan (i.e. read) input from a stream
- String
- The String class is a very special class in Java
- Short-cut syntax for creating String objects, just using string literals (enclosed in “”)
- Various ways to create a String object:
String s1 = new String();
String s2 = new String("John");
String s3 = "Mary";
String s4 = s3; // Refer to same object
- Simple example:
public static void demoString() {
Scanner scanner = new Scanner(System.in);
String firstName = scanner.next();
String lastName = scanner.next();
String fullName = firstName + " " + lastName;
String fullNameLC = fullName.toLowerCase();
System.out.println(fullNameLC);
}
- View code file.
- Here are some of the useful public methods in String:
- int length() // Note, this is a method!!!
- boolean equals(String s2)
- String toString()
- String substring(int begin, int end)
- String replace(char oldChar, char newChar)
- Etc…
- String objects are immutable
- Once created, you can’t change a String object
- All the String methods return a different String object instead
- For mutable strings:
- Use StringBuilder or StringBuffer (see later for details)
- Note:
- String literals (“like this”) are held in a string constant pool
- When the compiler encounters a string literal in your code, it tries to resolve it in the string constant pool
- The String class is a very special class in Java
- Math
- The java.lang package contains a Math class:
- Contains many mathematical methods and constants (all static!)
- Here are some of the methods:
- sin(), cos(), tan(), sinh(), cosh(), tanh()
- log(), log10(), exp()
- pow(), sqrt(), random()
- Etc…
- Here are some of the constants:
- PI, E
- Here’s an example of the Math class:
public static void demoMath() {
double angle = Math.PI / 4;
System.out.println("Sin: " + Math.sin(angle));
...
System.out.println("In degrees: " + Math.toDegrees(angle));
double radius = 10.0;
System.out.println("Circle area: " + Math.PI * radius * radius);
double num = -10.5;
System.out.println("Absolute value: " + Math.abs(num));
System.out.println("Max of num,20: " + Math.max(num, 20));
...
System.out.println("Random number: " + Math.random());
}
- View code file.
- The java.lang package contains a Math class:
- BigInteger and BigDecimal
- The java.math package contains two useful classes for manipulating very large numbers:
- BigInteger
- BigDecimal
- Example of BigInteger
- BigDecimal is same idea
import java.math.BigInteger;
...
public static void demoBigInteger() {
BigInteger gdp1 = new BigInteger("123456789012345678901234567890");
BigInteger gdp2 = new BigInteger("987654321098765432109876543210");
BigInteger totalGdp = gdp1.add(gdp2);
BigInteger avgGdp = totalGdp.divide(new BigInteger("2"));
System.out.println("Average GDP: " + avgGdp);
}
- View code file.
- BigDecimal is same idea
- The java.math package contains two useful classes for manipulating very large numbers:
- Using Math and StringBuilder
- Use the Math class to determine the minimum and maximum salaries
// Optional extra bit: Use Math classes.
double minSalary = Math.min(salary1, salary2);
double maxSalary = Math.max(salary1, salary2);
System.out.println("Minimum salary: " + minSalary + ", Maximum salary: " + maxSalary);
- Use the StringBuilder class to accumulate some useful information efficiently, and then display it. You can find information about StringBuilder in the online JavaDoc documentation
// Optional extra bit: Use StringBuilder class.
StringBuilder sb = new StringBuilder();
sb.append("Employee 1: ");
sb.append(name1);
sb.append(" earns ");
sb.append(salary1);
System.out.println(sb.toString());
// Close the scanner after use.
scanner.close();
- View code file.
- Use the Math class to determine the minimum and maximum salaries
Lab 6: Wrapper classes
- Overview
- For each of the 8 primitive types, there’s a corresponding “wrapper” class
- All in the java.lang package
- Wrap primitive values in an object, so they can be used where objects are expected
- The wrapper classes are:
- Byte
- Short
- Integer
- Long
- Etc…
- For each of the 8 primitive types, there’s a corresponding “wrapper” class
- Creating Wrapper Objects
- Each wrapper class (except Character) provides two constructors
- One that takes a primitive of the type being constructed
- One that takes a String representation of the type being constructed
Integer empCode1 = new Integer(65431);
Integer empCode2 = new Integer("65431");
- Character provides a single constructor
- Takes a char argument
Character initial = new Character('A');
- Takes a char argument
- Note:
- Wrapper objects are immutable after creation
- Each wrapper class provides a static valueOf() method
- Allows you to create a wrapper object based on a primitive value or a String
- Note, Character doesn’t have the String overload
Integer empCode1 = Integer.valueOf(65431);
Integer empCode2 = Integer.valueOf("65431");
- The whole-number wrapper classes (Byte, Short, Integer, Long) also let you specify a radix
Integer num1 = Integer.valueOf("1011001", 2); // 2 for binary
Integer num2 = Integer.valueOf("7064752", 8); // 8 for octal
Integer num3 = Integer.valueOf("6FDE075", 16); // 16 for hexadecimal
...
etc.
- Each wrapper class (except Character) provides two constructors
- Getting Primitive Values
- Each wrapper class provides a XxxValue() method
- intValue(), doubleValue(), charValue(), etc.
- Allows you to get the primitive value inside a wrapper object
Integer empCode = new Integer(65431);
Double salary = new Double(12345.67);
Character status = new Character('M');
int empCodeValue = empCode.intValue();
double salaryValue = salary.doubleValue();
char statusValue = status.charValue();
- Each wrapper class provides a XxxValue() method
- String Conversion Methods
- parseXxx()
- Static method in numeric wrapper classes
- Takes a numeric string parameter, and returns a primitive value
- Can cause a NumberFormatException
int i1 = Integer.parseInt("1011001", 2);
int i2 = Integer.parseInt("7064752", 8);
double d = Double.parseDouble("1234.56");
- toString()
- Instance method in all wrapper classes
- Plus overloaded static method (takes a primitive parameter)
Integer integer1 = new Integer(12345);
String str1 = integer1.toString();
String str2 = Integer.toString(12345);
- toBinaryString(), toOctalString(), toHexString()
- Static methods in Integer and Long classes
- Take an int or long parameter, and return a string in binary, octal, or hexadecimal format
String num1Binary = Integer.toBinaryString(12345);
String num1Octal = Integer.toOctalString(12345);
String num1Hex = Integer.toHexString(12345);
String num2Binary = Long.toBinaryString(123456789012345);
String num2Octal = Long.toOctalString(123456789012345);
String num2Hex = Long.toHexString(123456789012345);
- parseXxx()
Well done. You have completed the tutorial in the Java course. The next tutorial is
3. Operators and Flow Control
Copyright © 2016 TalkIT®
If you would like to see more content like this in the future, please fill-in our quick survey.