1 of 43

Agenda

  • Brief History of Java and overview of language
  • Solve a problem to demonstrate Java syntax
  • Discuss coding issues and style via example

Java Basics

1

2 of 43

Brief History of Java and Overview of Language

Java Basics

2

3 of 43

The history of Java starts with the Green Team. Java team members (also known as Green Team), initiated this project to develop a language for digital devices such as set-top boxes, televisions, etc. However, it was best suited for internet programming. Later, Java technology was incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the early '90s.

3

4 of 43

4

James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991. The small team of sun engineers called Green Team.

Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.

Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.

After that, it was called Oak and was developed as a part of the Green project. Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany, Romania, etc.

5 of 43

In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

The team gathered to choose a new name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to say.

According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique, most of the team members preferred Java than other names.

Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.

6 of 43

Java Version History

JDK Alpha and Beta (1995)

JDK 1.0 (23rd Jan 1996)

JDK 1.1 (19th Feb 1997)

J2SE 1.2 (8th Dec 1998)

J2SE 1.3 (8th May 2000)

J2SE 1.4 (6th Feb 2002)

J2SE 5.0 (30th Sep 2004)

Java SE 6 (11th Dec 2006)

Java SE 7 (28th July 2011)

Java SE 8 (18th Mar 2014)

Java SE 9 (21st Sep 2017)

7 of 43

Java SE 10 (20th Mar 2018)

Java SE 11 (September 2018)

Java SE 12 (March 2019)

Java SE 13 (September 2019)

Java SE 14 (Mar 2020)

Java SE 15 (September 2020)

Java SE 16 (Mar 2021)

Java SE 17 (September 2021)

Java SE 18 March 2022)

Java SE 19 (2023)

8 of 43

Top 10 Java IDE

    • IntelliJ IDEA
    • Eclipse
    • Apache NetBeans
    • MyEclipse IDE
    • BlueJ IDE
    • Xcode IDE
    • Jdeveloper IDE
    • JCreator IDE
    • DrJava IDE
    • Greenfoot IDE

9 of 43

What is Bytecode in Java?

Can you imagine a world where we have to write code multiple times for each device with varying specifications like operating system, processor architecture, etc.? It will be a tedious process. Keeping these things in mind, Java developers came up with the concept of Write Once Read Anywhere, which got incorporated as a feature in the Java language. To achieve this, a code known as bytecode gets generated after compiling our Java source code. We will now discuss the same.

10 of 43

Bytecode in Java is a set of instructions for the Java Virtual Machine. Java Virtual Machine, abbreviated as JVM, enables a computer to run code written in Java. When a Java program is compiled, the bytecode gets generated. It is equivalent to the assembler in C++.

Bytecode is a platform-independent set of instructions primarily because it is interpreted and executed by the JVM. Code that runs on multiple computer architectures without any modification is called machine or platform-independent code.

11 of 43

How Java Works

  • Java's platform independence is achieved by the use of the Java Virtual Machine
  • A Java program consists of one or more files with a .java extension
    • these are plain old text files
  • When a Java program is compiled the .java files are fed to a compiler which produces a .class file for each .java file
  • The .class file contains Java bytecode.
  • Bytecode is like machine language, but it is intended for the Java Virtual Machine not a specific chip such as a Pentium or PowerPC chip

Java Basics

11

12 of 43

More on How Java Works

  • To run a Java program the bytecode in a .class file is fed to an interpreter which converts the byte code to machine code for a specific chip.
  • Some people refer to the interpreter as "The Java Virtual Machine" (JVM)
  • The interpreter is platform specific because it takes the platform independent bytecode and produces machine language instructions for a particular chip
  • So a Java program could be run on any type of computer that has a JVM written for it.

Java Basics

12

13 of 43

A Picture is Worth…

Java Basics

13

The Interpreter is sometimes referred to as the Java Virtual Machine

The output of the compiler is .class file

14 of 43

So What!

  • The platform independence of Java may be a huge marketing tool, but is actually of little use to people learning Object Oriented Programming and Abstract Data Types
  • What is of use is the simplicity of the Java syntax and programming concepts
  • Java is a "pure" Object Oriented Language
    • encapsulation, inheritance, and polymorphism
    • all code must be contained in a class
    • no free functions (functions that do not belong to some class) like C++, although someone who wants to write messy Java code certainly can
    • Is OO the best programming paradigm?

Java Basics

14

15 of 43

HelloWorld.java

Java Basics

15

/**

* A simple program

*/

public class HelloWorld

{

public static void main(String[] args)

{

System.out.println("HELLO World!");

}

}

16 of 43

More on Java Programs

  • All code part of some class

public class Abc �{ //start of class Abc � /*all code in here!*/ �} // end of class Abc

  • The code for class Abc will be in a file named Abc.java
    • just a text file with the .java extension
    • a class is a programmer defined data type
  • A complete program will normally consist of many different classes and thus many different files

Java Basics

16

17 of 43

Java Language�Review of Basic Features

Java Basics

17

18 of 43

Basic Features

  • Identifiers
  • Data Types
    • primitives
    • classes / objects
  • Expressions and operators
  • Control Structures
  • Arrays
  • Methods
  • Programming for correctness
    • pre and post conditions
    • assertions

Java Basics

18

19 of 43

Identifiers in Java

  • letters, digits, _, and $ (don't use $. Can confuse the runtime system)
  • start with letter, _, or $
  • by convention:
    1. start with a letter
    2. variables and method names, lowercase with internal words capitalized e.g. honkingBigVariableName
    3. constants all caps with _ between internal words e.g. ANOTHER_HONKING_BIG_INDENTIFIER
    4. classes start with capital letter, internal words capitalized, all other lowercase e.g HonkingLongClassName
  • Why? To differentiate identifiers that refer to classes from those that refer to variables

Java Basics

19

20 of 43

Java Data Types

Java Basics

20

21 of 43

Data Types

  • Primitive Data Types
    • byte short int long float double boolean char

��

    • stick with int for integers, double for real numbers
  • Classes and Objects
    • pre defined or user defined data types consisting of constructors, methods, and fields (constants and fields (variables) which may be primitives or objects.)

Java Basics

21

//dataType identifier;

int x;

int y = 10;

int z, zz;

double a = 12.0;

boolean done = false, prime = true;

char mi = 'D';

22 of 43

Java Primitive Data Types

Java Basics

22

Data Type

Characteristics

Range

byte

8 bit signed integer

-128 to 127

short

16 bit signed integer

-32768 to 32767

int

32 bit signed integer

-2,147,483,648 to 2,147,483,647

long

64 bit signed integer

-9,223,372,036,854,775,808 to- 9,223,372,036,854,775,807

float

32 bit floating point number

+ 1.4E-45 to�+ 3.4028235E+38

double

64 bit floating point number

+ 4.9E-324 to�+ 1.7976931348623157E+308

boolean

true or false

NA, note Java booleans cannot be converted to or from other types

char

16 bit, Unicode

Unicode character, \u0000 to \uFFFF Can mix with integer types

23 of 43

What are Classes and Objects?

  • Class is synonymous with data type
  • Object is like a variable
    • The data type of the Object is some Class
    • referred to as an instance of a Class
  • Classes contain:
    • the implementation details of the data type
    • and the interface for programmers who just want to use the data type
  • Objects are complex variables
    • usually multiple pieces of internal data
    • various behaviors carried out via methods

Java Basics

23

24 of 43

Creating and Using Objects

  • Declaration - DataType identifier

Rectangle r1;

  • Creation - new operator and specified constructor

r1 = new Rectangle();

Rectangle r2 = new Rectangle();

  • Behavior - via the dot operator

r2.setSize(10, 20);

String s2 = r2.toString();

  • Refer to documentation for available behaviors (methods)

Java Basics

24

25 of 43

Built in Classes

Java has a large built in library of classes with lots of useful methods

Ones you should become familiar with quickly

  • String
  • Math
  • Integer, Character, Double

Java Basics

25

26 of 43

import

  • import is a reserved word
  • packages and classes can be imported to another class
  • does not actually import the code (unlike the C++ include preprocessor command)
  • statement outside the class block�import java.util.ArrayList;�import java.awt.Rectangle;�public class Abc{� // code for class Abc�}

Java Basics

26

27 of 43

More on import

  • can include a whole package
    • import java.util.*;
  • or list a given class
    • import java.util.Random;
  • instructs the compiler to look in the package for types it can't find defined locally
  • the java.lang.* package is automatically imported to all other classes.
  • Not required to import classes that are part of the same project in Eclipse

Java Basics

27

28 of 43

The String Class

  • String is a standard Java class
    • a whole host of behaviors via methods
  • also special (because it used so much)
    • String literals exist (no other class has literals)�String name = "Mike D.";
    • String concatenation through the + operator�String firstName = "Mike";�String lastName = "Scott";�String wholeName = firstName + lastName;
    • Any primitive or object on other side of + operator from a String automatically converted to String

Java Basics

28

29 of 43

Standard Output

  • To print to standard output use

System.out.print( expression ); // no newline

System.out.println( expression ); // newline

System.out.println( ); // just a newline

common idiom is to build up expression to be printed out

System.out.println( "x is: " + x + " y is: " + y );

Java Basics

29

30 of 43

Constants

  • Literal constants - "the way you specify values that are not computed and recomputed, but remain, well, constant for the life of a program."
    • true, false, null, 'c', "C++", 12, -12, 12.12345
  • Named constants
    • use the keyword final to specify a constant
    • scope may be local to a method or to a class
  • By convention any numerical constant besides -1, 0, 1, or 2 requires a named constant

final int NUM_SECTIONS = 3;

Java Basics

30

31 of 43

Expressions and Operators

Java Basics

31

32 of 43

Operators

  • Basic Assignment: =
  • Arithmetic Operators: +, -, *, /, %(remainder)
    • integer, floating point, and mixed arithmetic and expressions
  • Assignment Operators: +=, -=, *=, /=, %=
  • increment and decrement operators: ++, --
    • prefix and postfix.
    • avoid use inside expressions.

int x = 3;�x++;

Java Basics

32

33 of 43

Expressions

  • Expressions are evaluated based on the precedence of operators
  • Java will automatically convert numerical primitive data types but results are sometimes surprising
    • take care when mixing integer and floating point numbers in expressions
  • The meaning of an operator is determined by its operands

/

is it integer division or floating point division?

Java Basics

33

34 of 43

Casting

  • Casting is the temporary conversion of a variable from its original data type to some other data type.
    • Like being cast for a part in a play or movie
  • With primitive data types if a cast is necessary from a less inclusive data type to a more inclusive data type it is done automatically.

int x = 5;�double a = 3.5;�double b = a * x + a / x;�double c = x / 2;

  • if a cast is necessary from a more inclusive to a less inclusive data type the class must be done explicitly by the programmer
    • failure to do so results in a compile error.�double a = 3.5, b = 2.7;�int y = (int) a / (int) b;�y = (int)( a / b );�y = (int) a / b; //syntax error

Java Basics

34

CS 307 Fundamentals of Computer Science

35 of 43

Primitive Casting

Java Basics

35

CS 307 Fundamentals of Computer Science

double

float

long

int

short,�char

byte

Outer ring is most�inclusive data type.�Inner ring is least

inclusive. ��In expressions

variables and

sub expressions

of less inclusive

data types are

automatically cast

to more inclusive.�

If trying to place

expression that is

more inclusive into

variable that is less

inclusive, explicit cast

must be performed.

From MORE to LESS

36 of 43

Java Control Structures

Java Basics

36

37 of 43

Control Structures

  • linear flow of control
    • statements executed in consecutive order
  • Decision making with if - else statements

if(boolean-expression)� statement;�if(boolean-expression)�{ statement1;� statement2;� statement3;�}�A single statement could be replaced by a statement block, braces with 0 or more statements inside

Java Basics

37

38 of 43

Boolean Expressions

  • boolean expressions evaluate to true or false
  • Relational Operators: >, >=, <, <=, ==, !=
  • Logical Operators: &&, ||, !
    • && and || cause short circuit evaluation
    • if the first part of p && q is false then q is not evaluated
    • if the first part of p || q is true then q is not evaluated

//example�if( x <= X_LIMIT && y <= Y_LIMIT)� //do something

Java Basics

38

39 of 43

More Flow of Control

  • if-else:�if(boolean-expression)� statement1;�else� statement2;
  • multiway selection:�if(boolean-expression1)� statement1;�else if(boolean-expression2)� statement2;�else� statement3;
  • individual statements could be replaced by a statement block, a set of braces with 0 or more statements
  • Java also has the switch statement, but not part of our subset

Java Basics

39

40 of 43

for Loops

  • for loops�for(init-expr;boolean-expr;incr-expr)� statement;
  • init-expr and incr-expr can be more zero or more expressions or statements separated by commas
  • statement could be replaced by a statement block

Java Basics

40

execute� init-expr

evaluate �boolean-expr

false

skip to 1st statement after�body of loop

true

execute�body of loop

execute�incr-expr

41 of 43

while loops

  • while loops�while(boolean-expression)� statement; //or statement block
  • do-while loop part of language�do� statement;�while(boolean-expression);
  • Again, could use a statement block
  • break, continue, and labeled breaks
    • referred to in the Java tutorial as branching statements
    • keywords to override normal loop logic
    • use them judiciously (which means not much)

Java Basics

41

42 of 43

Enhanced for loop

  • New in Java 5.0
  • Also known as the for-each loop
  • useful short hand for accessing all elements in an array (or other types of structures) if no need to alter values
  • alternative for iterating through a set of values

for(Type loop-variable : set-expression)

statement

  • logic error (not a syntax error) if try to modify an element in array via enhanced for loop

Java Basics

42

43 of 43

Enhanced for loop

Java Basics

43

public static int sumListEnhanced(int[] list)

{ int total = 0;

for(int val : list)

{ total += val;

System.out.println( val );

}

return total;

}

public static int sumListOld(int[] list)

{ int total = 0;

for(int i = 0; i < list.length; i++)

{ total += list[i];

System.out.println( list[i] );

}

return total;

}