<>
× Home

Expressions, Statements & More

Keywords and Expressions

Java Language Specification

  • Java Language Specification provides detailed documentation about how Java works.
  • Keywords are fundamental components of the Java language.
  • The specification includes a list of the 51 reserved keywords that have predefined meanings.
  • These keywords are part of the core syntax and structure of Java programming.
  • Starting from Java 9, the underscore by itself is also considered a keyword. Java 9 introduced this change to enhance the language's capabilities.
  • Additionally, Java 17 introduced 16 contextual keywords, which serve specific purposes only in certain situations.

Contextual Keywords

  • Contextual keywords are a recent addition to the Java language, introduced with JDK 17.
  • These keywords have specific meanings only in particular contexts or situations.
  • They allow for more nuanced and precise programming constructs.
  • Contextual keywords are an example of Java's ongoing evolution to cater to diverse programming needs.

Expression Overview

  • Expressions compute to single values.
  • Expressions built using values, variables, and operators.
  • Java highlights keywords in blue for identification.
  • Expressions consist of variables, values, and operators.
  • Expressions are integral components of statements.
  • Java requires valid data types and syntax for expressions.

Examples of Expressions

                    
double kilometers = (100 * 1.609344);
                    
                
  • Expressions combine variables, values, and operators.
  • Java expressions calculate conversions, perform operations, and more.

Using Expressions in Statements

                    
int highScore = 50;
if (highScore > 25) {
    highScore = 1000 + highScore; // add bonus points
}
    
  • Expressions are crucial in if statement conditions.
  • Expressions influence control flow and decision-making in code.

Statements, Whitespace and Indentation (Code Organization)

                
int myVariable = 50;
myVariable++;
myVariable--;

System.out.println("This is a test");

Whitespace and Readability

  • Whitespace includes horizontal and vertical spacing for readability.
  • Java ignores whitespace, so extra spaces are for human convenience.
  • Proper indentation and spacing enhance code readability.
  • Consistent formatting helps developers understand code flow.
  • Whitespace rules are defined in style guides like Google's Java Conventions.
  • IntelliJ offers automatic code reformatting for adherence to best practices.
                
int anotherVariable = 50;
myVariable--;
System.out.println("myVariable = " + myVariable);

Indentation for Clarity

  • Indentation improves visual structure and logic in code.
  • Indentation helps denote code blocks and their relationships.
  • Using tabs or spaces consistently ensures proper indentation.
  • Automatic indentation tools like IntelliJ assist in maintaining clarity.
  • Code indentation follows conventions set by style guides for consistency.
                
if (myVariable == 0) {
        System.out.println("It's now zero");
}

Code blocks And The If Then Else Control Statement

Using the If-Then Statement

The if statement checks a condition and executes code if the condition is true.

The code within the code block associated with the if statement is executed only if the condition evaluates to true.

It's important to include a code block even for single statements to enhance code readability.

Basic If Statement Example

                    
boolean gameOver = true;
int score = 5000;

if (score == 5000) {
    System.out.println("Your score was 5000");
}
    
    

In this example, the if statement checks if the score is equal to 5000.

If the condition is true, the associated code block is executed.

Using the Else-If and Else Blocks

An if statement can be extended with 'else-if' and 'else' blocks.

'Else-if' blocks provide additional conditions to check if the initial condition is false.

The 'else' block is executed if none of the previous conditions are true.

Conditions are evaluated in order, and the first true condition's code block is executed.

If-Else Example

                    
if (score < 5000) {
    System.out.println("Your score was less than 5000");
} else {
    System.out.println("Got here");
}
    
    

In this example, the else block is executed when the if condition is false.

If-Else-If Example

                      
if (score < 5000 && score > 1000) {
    System.out.println("Your score was less than 5000 but greater than 1000");
} else if (score < 1000) {
    System.out.println("Your score was less than 1000");
} else {
    System.out.println("Got here");
}
    
    

This example demonstrates the use of 'else-if' and 'else' blocks.

The code within the first true condition's block is executed.

If no conditions are true, the 'else' block is executed.

Methods in Java

Definition of a Method

Java's description of a method is that it declares executable code that can be invoked, passing a fixed number of values as arguments.

Methods are executed by calling or invoking them, and they have a name, parameters, and a method body.

Benefits of Methods

Methods help reduce code duplication by allowing code to be written once and reused multiple times.

They enable passing data to the method as arguments, allowing the same method code to work with different inputs.

Code Duplication Example

                    
// Code duplication example
// Problem: Changing code in one place may lead to errors in other similar code blocks
// Solution: Methods can help eliminate code duplication

public class MainChallenge {
    public static void main(String[] args) {
        // ...
        int finalScore = score + (levelCompleted * bonus);
        // ...
    }
}
    

This code duplication example highlights the challenge of maintaining similar code blocks and the potential for errors.

Creating a Simple Method

                    
// Basic method structure
public static void methodName() {
    // Method body or code block
    // Code to be executed when the method is called
}
    

Methods are defined with a name, a parameter list (if any), and a code block.

The public static void keywords indicate accessibility and return type.

Creating a Method: calculateScore

                    
public static void calculateScore() {
    // Method body
    // Code to calculate the score
}
    

Creating a new method named calculateScore to encapsulate score calculation logic.

Method names follow lower camel case naming convention.

Calling a Method

                    
public static void main(String[] args) {
    // ...
    calculateScore(); // Calling the method
    // ...
}
    

Methods are called or invoked using their names followed by parentheses.

The method code block is executed when the method is called.

Passing Arguments to a Method

                    
// Method declaration with parameters
public static void calculateScore(boolean gameOver, int score, int levelCompleted, int bonus) {
    // Method body using parameters
    // Code that uses the provided arguments
}
    

Methods can accept arguments (parameters) to work with specific data passed from the calling code.

Arguments are defined in the method declaration, specifying data type and variable name.

Invoking a Method with Arguments

                    
public static void main(String[] args) {
    // ...
    calculateScore(true, 800, levelCompleted, bonus); // Calling method with arguments
    // ...
}
    
    

When calling a method with arguments, provide values or expressions that match the parameter types.

Arguments must be provided in the exact order and type defined in the method declaration.

More on Methods

Return Types and Return Statements

Methods can be declared to have return types, similar to how variables have types.

Return types indicate the type of value the method will return when it completes execution.

The return statement is used to send a value back from the method to the calling code.

Method Declaration with Return Type

                    
public static int methodName() {
    // Method body
    // Code to calculate and return an int value
    return result;
}
    
    

Methods with return types specify the type of data they will return in the declaration.

The return statement is used to provide the value to be returned.

Returning a Value from a Method

                    
public static int calculateScore() {
    // Method body
    int finalScore = score + (levelCompleted * bonus);
    return finalScore; // Returning the calculated value
}
    
    

Methods can return a value by using the return statement followed by the value.

The value being returned must match the declared return type of the method.

Using the Returned Value

                    
public static void main(String[] args) {
    // ...
    int highScore = calculateScore();
    System.out.println("The highScore is " + highScore);
    // ...
}
    
    

The returned value from a method can be assigned to a variable and used in the calling code.

Calling a method with a return type in an expression allows for data exchange between the method and the calling code.

Ignoring the Returned Value

                    
public static void main(String[] args) {
    // ...
    calculateScore(); // Return value ignored
    // ...
}
    
    

If the returned value from a method is not used or assigned, it is ignored by the calling code.

The compiler and IDE do not raise an error for ignoring the returned value.

Using Method Calls in Expressions

                    
public static void main(String[] args) {
    // ...
    System.out.println("The next highScore is " + calculateScore());
    // ...
}
    
    

Method calls that return a value can be used directly within expressions.

The returned value is treated as a part of the expression, like any other variable.

Methods Recap

Method Basics

  • Java's documentation defines a method as executable code that takes arguments.
  • Method can be a statement or expression.
  • Method returns a value can be an expression.
  • Method that doesn't return a value can be a procedure.

Method Declaration

  • Declare modifiers like public, static.
  • Declare the return type (void, primitive data type, or class).
  • Code block must have at least one return statement if return type defined.
  • Declare method name in lower camel case.
  • Declare method parameters in parentheses.
  • Method block with opening and closing curly braces.

Parameters and Arguments

  • Parameters defined as a list of comma-separated specifiers.
  • Parameter order matters when calling the method.
  • Arguments must match the parameters in type and number.

Return Statements

  • Void is a valid return type meaning no data is returned.
  • Other return types require a return statement in the code block.
  • If return type defined, return statement required at all exit points.
  • All code segments in nested blocks must return a value.
  • Option to return with no value from a void method.
  • No need for a return statement at the end of a void method.

Method Signature and Overloading

  • Method uniquely defined by name and parameters (method signature).
  • Multiple methods with the same name but different parameters can exist.
  • Overloaded methods have the same name but different parameters.

Main Method

  • Main method is special in Java and serves as entry point.
  • Main method has specific modifiers (public, static).
  • Main method has void return type.
  • Main method accepts args parameter as an array of Strings.

Method Overloading

Method Overloading

  • Method overloading involves multiple methods with the same name but different parameters
  • Java resolves which method to execute based on arguments passed during invocation
  • Allows creating methods with the same name but varying types and numbers of arguments
  • Method signature includes method name and parameter uniqueness
  • Parameter names and return types aren't part of the signature

Overloaded Methods Example

                    
public static int calculateScore(String playerName, int score) { ... }
public static int calculateScore(int score) { ... }
public static int calculateScore() { ... }
                
            
  • Example of method overloading with the same method name
  • Different parameter lists based on parameter count and types

Invalid Overloaded Methods Example

                    
public static void printInfo(String name, int age) { ... }
public static void printInfo(int age, String name) { ... } // Invalid (same parameter types but different order)
public static void printInfo(String name, int id) { ... } // Invalid (different parameter types)
public static int printInfo(String name, int age) { ... } // Invalid (different return type)
                
            
  • Examples of invalid overloaded methods
  • Method signatures must differ by parameter types, order, or count
  • Return types are not considered for overloading

Using Overloaded Methods

                    
public static int calculateScore(String playerName, int score) { ... }
public static int calculateScore(int score) { ... }
public static int calculateScore() { ... }
                
            
  • Overloading allows creating methods with default values
  • Default values not directly supported in Java
  • Using method overloads to achieve similar functionality