Java Intro

--from Zero to Hero

Created by Junchao for CodingGirls

About

  • Junchao, PRO Unlimited@Facebook, Software Engineer
  • Ann, Advance AI, Data Engineer & CodingGirls, CEO

Java

Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
--Wikipedia

Java

  • The most popular programming language
  • Object-oriented
  • Static typing
  • "Compile once, run anywhere."
  • It has pratically nothing to do with JavaScript

Outline

  • Hello, World!
  • Variables, methods and program
  • Data Types
  • Control Flow
  • Object Oriented

Hello, World!

Code

      
// file: HelloWorldApp.java
class HelloWorldApp {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
      
    

Compile and run

  • Compile:
    javac HelloWorldApp.java
  • See output:
    ls
  • Run:
    java HelloWorldApp
  • See output: what is on screen?

Explanation

      
// file: HelloWorldApp.java
// The line above is comment
/*
You can also create a block of comment this way
usually // for inline comments
*/
/* for block comments */
// Now we are creating a class
// the name of the class is HelloWorldApp, which matches the filename
class HelloWorldApp {
    // the entry point: main method
    public static void main(String[] args) {
        // print out the message to the command line
        System.out.println("Hello, World!");
    }
}
      
    

More doubts

  • Class name and file name must match?
  • Yes for public classes
  • What is public? Then do we have private?
  • public means anyone can access. private and protected also exist
  • What does static means?
  • Means this method is bound to the class instead of the object
  • What does String[] means? what does System.out.println mean?
  • We will come to this

Variables, methods and program

Variables

In computer programming, a variable or scalar is a storage location (identified by a memory address) paired with an associated symbolic name (an identifier), which contains some known or unknown quantity of information referred to as a value.
  • Variables in method definition are called parameters
  • String[] args
    is the parameter

More on variables

  • A name: identifier
  • A value: the actual value
  • Combined to a variable

Methods

A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object is mostly made up of data and behavior, which form the interface that an object presents to the outside world. Data is represented as properties of the object and behavior as methods. For example, a Window object would have methods such as open and close, while its state (whether it is opened or closed) would be a property.

More on methods

  • defined on object/class
  • represent a bahavior of the object/class
  • another way of looking at it: function bound to object/class
  • another way of looking at it: message sent to object

Program

A computer program is a collection of instructions that performs a specific task when executed by a computer. A computer requires programs to function.

Notes

  • Do not get too caught up with definitions
  • "I do and I understand"

Data Types

Basic Data Types

  • boolean
  • byte
  • char
  • short
  • int
  • long
  • float
  • double
  • String
  • Array
  • More

boolean

  • True or False. Nothing less and nothing more
  • Size: 1 bit (usually)

Integral

  • byte, short, int, long
  • Size: 1, 2, 4, 8 bytes
  • Integer with different size and range

Floating-point

  • float, double
  • Size: 4, 8 bytes
  • represent decimal up to some precesion

String

  • A sequence of chars
  •         
    // StringDemo1.java
    public class StringDemo1 {
       public static void main(String args[]) {
          char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
          String helloString = new String(helloArray);  
          System.out.println( helloString );
       }
    }
    // StringDemo2.java
    public class StringDemo2 {
       public static void main(String args[]) {
          String string1 = "saw I was ";
          System.out.println("Dot " + string1 + "Tod");
       }
    }
            
          

Array

  • A sequence of same-type values
  •         
    // TestArray1.java
    public class TestArray1 {
       public static void main(String[] args) {
          double[] myList = {1.9, 2.9, 3.4, 3.5};
    
          // Print all the array elements
          for (int i = 0; i < myList.length; i++) {
             System.out.println(myList[i] + " ");
          }
         
          // Summing all elements
          double total = 0;
          for (int i = 0; i < myList.length; i++) {
             total += myList[i];
          }
          System.out.println("Total is " + total);
          
          // Finding the largest element
          double max = myList[0];
          for (int i = 1; i < myList.length; i++) {
             if (myList[i] > max) max = myList[i];
          }
          System.out.println("Max is " + max);  
       }
    }
            
          

Control Flow

  • if-else
  • for
  • while
  • break and continue
  • exception and try-catch

if-else

Programmer's wife told him: "buy 10 dumplings. If u see somebody selling watermelon, then buy one."

And the programmer came home with one dumpling. The wife was angry: "Why only 1 dumpling".

Programmer: "Because I saw a watermelon-man..."

What is wrong?

if-else

      
int dumplingsToBuy = 10;
if (seeWatermelonMan) {
    dumplingsToBuy = 1;
}
buy(dumplingsToBuy);
// end of story
      
    
      
int dumplingsToBuy = 10, watermelonsToBuy = 0;
if (seeWatermelonMan) {
    watermelonsToBuy = 1;
}
buy(dumplingsToBuy);
buy(watermelonsToBuy);
// what the wife meant
      
    

if-else

      
if (condition) {
    statementsToExecuteIfConditionIsTrue;
} else {
    statementsToExecuteIfConditionIsFalse;
    if (condition2) {
        statementsIfConditionFalseAndCondition2True;
    }
}
      
    

for

      
for(declaration : expression) {
   // Statements
}
for(init;end check;increment) {
  // Statements
}
// ForTest.java
public class ForTest {
   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
      for(int x : numbers ) {
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      for(int i = 0; i < numbers.length; i++) {
         System.out.print(numbers[i]);
         System.out.print(",");
      }
      System.out.print("\n");

      String [] names = {"James", "Larry", "Tom", "Lacy"};
      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
      System.out.print("\n");
   }
}
      
    

while

      
// while loop
while (condition) {
  // Statements
}
// do while loop
do {
  // Statements
} while (condition);
      
    

break and continue

break: Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

continue: Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

exception and try-catch

      
try {
   // Protected code
} catch (ExceptionName e1) {
   // Catch block
}
// File Name : ExceptTest.java
import java.io.*;

public class ExceptTest {

   public static void main(String args[]) {
      try {
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}
      
    

Object Oriented

  • Ideas
  • Constructor
  • Methods

Ideas

Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class.

Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.

Ideas

Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.

Instance Variables − Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.

Constructor and methods

      
public class Puppy {
   int puppyAge;

   public Puppy(String name) {
      // This constructor has one parameter, name.
      System.out.println("Name chosen is :" + name );
   }

   public void setAge( int age ) {
      puppyAge = age;
   }

   public int getAge( ) {
      System.out.println("Puppy's age is :" + puppyAge );
      return puppyAge;
   }

   public static void main(String []args) {
      /* Object creation */
      Puppy myPuppy = new Puppy( "tommy" );

      /* Call class method to set puppy's age */
      myPuppy.setAge( 2 );

      /* Call another class method to get puppy's age */
      myPuppy.getAge( );

      /* You can access instance variable as follows as well */
      System.out.println("Variable Value :" + myPuppy.puppyAge );
   }
}
      
    

Constructor and methods

      
import java.io.*;
public class Employee {

   String name;
   int age;
   String designation;
   double salary;

   // This is the constructor of the class Employee
   public Employee(String name) {
      this.name = name;
   }

   // Assign the age of the Employee  to the variable age.
   public void empAge(int empAge) {
      age = empAge;
   }

   /* Assign the designation to the variable designation.*/
   public void empDesignation(String empDesig) {
      designation = empDesig;
   }

   /* Assign the salary to the variable salary.*/
   public void empSalary(double empSalary) {
      salary = empSalary;
   }

   /* Print the Employee details */
   public void printEmployee() {
      System.out.println("Name:"+ name );
      System.out.println("Age:" + age );
      System.out.println("Designation:" + designation );
      System.out.println("Salary:" + salary);
   }
}
      
    

Future learning

  • Web development: Spring
  • GUI development: JavaFX
  • Android development: Android Studio and Kotlin
  • Big Data development: Hadoop and Scala

Take-aways

  • How to write and run a simple java program
  • What are different data types
  • How to control the flow of program
  • What are object, class and object-oriented?

Thank you