java logo

Java Tutorial

Prepared for PEO Mississauga Chapter

Online High School Coding Challenge 2023

A Quick Introduction

My name is Les Carbonaro.

I am a software developer, mainly full-stack web application development.

I also host a beginner-friendly meet-up group called Mississauga Coding.

Pre-requisites

Either download and install the JDK and a code editor or IDE.

Or, use one of the many online Java compilers available.

Will be using OnlineGDB for all the examples in this tutorial.

Why Learn/Use Java?

  • Versatile & portable across platforms & applications
  • Used across several industries
  • In high demand
  • Excellent community support
  • Clearly structured applications
java-fun-fact

Who invented Java?

James Gosling started developing Java in 1991 while working for Sun Microsystems.

Basic File Structure

Basic Source File Structure

              
        
              
            

Basic Source File Structure

              
                // 1. everything needs to be inside a class
                public class Main {
                  


                }  
              
            

Basic Source File Structure

              
                // 1. everything needs to be inside a class
                public class Main {

                  // 2. every class needs at least one method
                  public static void main(String[] args) {
                    

                  }

                }  
              
            

Basic Source File Structure

          
            // 1. everything needs to be inside a class
            public class Main {

              // 2. every class needs at least one method
              public static void main(String[] args) {
                

              }

            }  
          
        

Basic Source File Structure

              
                // 1. everything needs to be inside a class
                public class Main {

                  // 2. every class needs at least one method
                  public static void main(String[] args) {
                    /* 
                    a method contains programming logic                
                    */                    
                  } // end of method block 

                  // other methods, if any, go here

                }  // end of class block
              
            

Outputs

          
            // 1. everything needs to be inside a class
            public class Main {

              // 2. every class needs at least one method
              public static void main(String[] args) {

                /* 
                a method contains programming logic                
                */
                
                // some output message
                System.out.println("Hello World");

              }

            }  
          
        

Some Variable Types

(The most commonly used)

  • int
  • float
  • double
  • boolean
  • char
  • String

Variable Type Conversion

(Also known as Casting)

Think of variables as boxes in memory.

The size of the box depends on the variable type.

Automatic or implicit - when going to a bigger box

Manual or explicit - when going to a smaller box

Inputs

Programs typically need input(s).

One way is to prompt user to enter a value.

Java has built-in methods for this purpose.

Inputs

          
            import java.util.Scanner;
            public class Main {
              
              public static void main(String[] args) {

                Scanner scan = new Scanner(System.in);

                System.out.println("What is your name:");
                String name = scan.nextLine();
              
                System.out.println("Hello " + name);

              }

            }  
          
        

Inputs cont.

          
            // 1. import the required Java libraries
            import java.io.InputStreamReader;
            import java.io.BufferedReader;
            import java.util.StringTokenizer;
            import java.io.IOException;            
            
            public class Main {
            	public static void main(String[] args) {
            		System.out.println("Enter item qty price");
            		
            		// 2. set up readers & tokeniser
            		InputStreamReader isr = new InputStreamReader( System.in );
            		BufferedReader br = new BufferedReader(isr);
            		StringTokenizer st = null;  
            		
            		// 3. read input line
            		// note that must catch exception
            		try {
                    st = new StringTokenizer(br.readLine());
                } catch(IOException e) {
                    e.printStackTrace();
                }
            		
            		// 4. tokenise (chop up) the input into respective variables
            		// note parse methods for int, float            		
            		String item = st.nextToken();
                int qty = Integer.parseInt( st.nextToken() );
            		float price = Float.parseFloat( st.nextToken() );
            		
            		// use input variables as needed
            		System.out.println("input item is: " + item);
            		System.out.println("input qty is: " + qty);
            		System.out.println("input price is: " + price);
            	}
            }
          
        

Some Useful String methods

.length()

.equals(String s)

.charAt(int i)

.substring(int start, int len)

java-fun-fact

What was Java called originally?

Java was originally called Oak, after a tall oak tree outside James Gosling's office window.

Operators

Arithmetic

+ - * / % ++ --

Assignment

= += -=

Some Useful Math methods

Math.pow(base,power)

Math.random()

More Operators

Comparison

== < <= > >= !=

Logical

&& (AND) || (OR)

Conditional Statements

(a.k.a. IF statements)

If something is true then do this, otherwise do that.

            
              if( condition ) {  // if block
                // do something
              } else {  // else block
                // do some other thing
              }             
            
          

Arrays

A list or group of values; a collection

Multiple values in one variable

- fixed number of values

- same data type

- access by zero-based index

- can be multi-dimensional

For-Loop Statements

For

            
            for( initialise; check; increment ) {

              // Code to be executed on each iteration
        
            }
            
          

For-Each

            
            for(dataType variableName : arrayName) {

              // Code to be executed on each element
      
            }
            
          

While-Loop Statements

While

            
            while(condition) {

                // Code to be executed as long as the condition is true

            }            
            
          

Do-While

            
            do {

                // Code to be executed at least once

            } while(condition);                      
            
          

Switch-Case Statement

            
            switch(variable) {
              case value1:
                // code to be executed if expression matches value1
                break;
              case value2:
                // code to be executed if expression matches value2
                break;              
              // additional case statements if needed
              default:
                // code to be executed if none of the above cases match
            }
            
          

Methods

(a.k.a. functions in other languages)

Reusable snippets of code

- DRY principle

- divide & conquer

- better code organisation, reusability, and modularity

Methods cont.

            
            accessModifier returnType methodName(parameterList) {
              
                // code to be executed
            
                // optionally, a return statement to return a value
            
            }            
            
          

Define method once

Call it as many times as needed

java-fun-fact

What year was Java launched?

Java 1.0 came out in 1996.

Object-Oriented Programming

Custom-made classes

- variables and related methods

            
            public class ClassName {

                // Class attributes (a.k.a. variables, properties, fields)
            
                // Class methods
            
            }                  
            
          

OOP cont.

Classes vs Objects

- class is the blueprint

- object is a variable made from that blueprint

An object is an instance of a class

Where To Find More

Any questions?

Thank You