SlideShare a Scribd company logo
1 of 16
Introduction to Java 2
    Programming
       Lecture 2
      Java Syntax
Overview
• Java Syntax
  – The Basics
  – Classes, Packages
Naming
• All Java syntax is case sensitive
• Valid Java names
   – Consist of letters, numbers, underscore, and dollar
   – Names can only start with letter or underscore
   – E.g. firstAttribute but not 1stAttribute
• “Camel case” convention
   – Java encourages long, explanatory names
   – Start with a lower case letter, with words capitalised
   – E.g. thisIsCamelCase, andSoIsThisAsWell
Java Types
• Java has two basic types
   – Primitive types
   – Reference Types
• Primitive types
   – integers, floating point numbers, characters, etc
   – Refer to actual values
• Reference types
   – Arrays, Classes, Objects, etc
   – Refer to memory locations (by name, not location)
Primitive Types
Type                  Description                 Size
Boolean (boolean)     True/false value            1 bit
Byte (byte)           Byte-length integer         1 byte
Short (short)         Short integer               2 bytes
Integer (int)         Integer                     4 bytes
Long (long)           Long Integer                8 bytes
Float (float)         Single precision floating   4 bytes
                      point number
Double (double)       Double precision float      8 bytes
Char (char)           Single character            2 bytes
Syntax Examples (Variables)
int anInteger;
Boolean isSwitchOn;

Variables can be initialised when they are declared

Int anInteger = 10;
Boolean isSwitchOn = true;
Syntax Examples (if)
if (x == y)
{
   //executes if true
}

if (somethingIsTrue())
{
  doSomething();
}
else
{
  doSomethingElse();
}
Example (for)
int x=0;
for (int i=1; i<=10; i++)
{
  //code to repeat ten times
  x = x + i;
}
Example (while)
int x=0;
while (x < 10)
{
  doSomething();
  x++;
}

//loop forever
while (true)
{
}
Methods
• Define some behaviour of a class
• Method declarations have four basic
  sections, and a method body:
  –   Visibility modifier (who can call the method)
  –   Return type (what does it return)
  –   Method name
  –   Parameter list (what parameters does it accept)
Syntax Examples (Methods)
public void calculatePayroll()
{
  //code goes here
}

private int addNumbers(int x, int y)
{
  //code goes here
}
Method Naming Conventions
• If a method sets some value on an object
public void setVatLevel(float vat);
• If a method retrieves some value from the
  object
public float getTotalPayroll();
• If a method returns a boolean value
public boolean isSwitchOn();
Classes
• One Java class defined in each .java file
• File name must match the name of the class
  – Otherwise there will be compilation errors
  – Class names start with an upper case letter
• Compiler will generate a .class file with
  same name
  – Contains the bytecode
• Classes defined using the class keyword.
Packages
• Group related classes together
• Each class in a package must have a unique name
• Indicate the package a class belongs to with the
  package keyword
• Recommended each class is put in a package
• Gain access to public classes in other packages
  using the import keyword
   – The JVM needs to know where the classes are defined
     before you can use them
Anatomy of a Java Source File
package intro2java;
import java.util.*;

/**
 * A description of the class
 */
public class MyFirstClass {
  //attributes
  private boolean isSomething;
  private int aCounter;

    //methods
    public void doSomething()
    {
      //code goes here
    }
}
Common Sources of Error
• Mistakes in naming
   – Wrong case, illegal names
   – class name and source file name not the same
• Missing semi-colon
• Missing curly brackets
• Incorrect Loop checks
   – Loop is too large/small, or occurs forever
• Testing equality
   – Assignment with = (single equals sign)
   – Comparison with == (two equals signs)

More Related Content

What's hot

2 variables and data types
2   variables and data types2   variables and data types
2 variables and data typesTuan Ngo
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in pythonJothi Thilaga P
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in PythonJuan-Manuel Gimeno
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 
Data types in python lecture (2)
Data types in python lecture (2)Data types in python lecture (2)
Data types in python lecture (2)Ali ٍSattar
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and javaMadishetty Prathibha
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocksİbrahim Kürce
 
Primitive data types in java
Primitive data types in javaPrimitive data types in java
Primitive data types in javaUmamaheshwariv1
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : PythonRaghu Kumar
 

What's hot (19)

2 variables and data types
2   variables and data types2   variables and data types
2 variables and data types
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
 
Java Datatypes
Java DatatypesJava Datatypes
Java Datatypes
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Introduction to Prolog
Introduction to PrologIntroduction to Prolog
Introduction to Prolog
 
Logic Programming and ILP
Logic Programming and ILPLogic Programming and ILP
Logic Programming and ILP
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Smali语法
Smali语法Smali语法
Smali语法
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in Python
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Data types in python lecture (2)
Data types in python lecture (2)Data types in python lecture (2)
Data types in python lecture (2)
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
 
Understanding Python
Understanding PythonUnderstanding Python
Understanding Python
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Java unit 2
Java unit 2Java unit 2
Java unit 2
 
Primitive data types in java
Primitive data types in javaPrimitive data types in java
Primitive data types in java
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 

Viewers also liked

Le illusioni di_octavio_ocampo
Le illusioni di_octavio_ocampoLe illusioni di_octavio_ocampo
Le illusioni di_octavio_ocampoEDUPEL
 
Media studies as_questionnaire_graphed_results
Media studies as_questionnaire_graphed_resultsMedia studies as_questionnaire_graphed_results
Media studies as_questionnaire_graphed_resultsJoeSpencerCross
 
mitad del mundo by tania leon
mitad del mundo by tania leonmitad del mundo by tania leon
mitad del mundo by tania leontania28leon
 
ИС на вашей работе
ИС на вашей работеИС на вашей работе
ИС на вашей работеAnna Sviridova
 
natural reserves in ecuador by tania leon
natural reserves in ecuador by tania leonnatural reserves in ecuador by tania leon
natural reserves in ecuador by tania leontania28leon
 
Изображения в ИТ
Изображения в ИТ Изображения в ИТ
Изображения в ИТ Anna Sviridova
 
001المدونات
 001المدونات 001المدونات
001المدوناتr84only
 
Oficina Arduino - Jornada de Tecnologia 2014 (E-poti) - Part II
Oficina Arduino - Jornada de Tecnologia 2014 (E-poti) - Part IIOficina Arduino - Jornada de Tecnologia 2014 (E-poti) - Part II
Oficina Arduino - Jornada de Tecnologia 2014 (E-poti) - Part IICarlos Carvalho
 
The short film context part 6
The short film context part 6The short film context part 6
The short film context part 6JoeSpencerCross
 
Materi Fungsi/Pemetaan oleh Yudi Prasetyo, S.Pd
Materi Fungsi/Pemetaan oleh Yudi Prasetyo, S.PdMateri Fungsi/Pemetaan oleh Yudi Prasetyo, S.Pd
Materi Fungsi/Pemetaan oleh Yudi Prasetyo, S.PdRadityo Pras
 
InfoPI 2013 - Minicurso - Introdução ao CUDA - Segunda Parte
InfoPI 2013 - Minicurso - Introdução ao CUDA - Segunda ParteInfoPI 2013 - Minicurso - Introdução ao CUDA - Segunda Parte
InfoPI 2013 - Minicurso - Introdução ao CUDA - Segunda ParteCarlos Carvalho
 

Viewers also liked (18)

Lesson3
Lesson3Lesson3
Lesson3
 
Le illusioni di_octavio_ocampo
Le illusioni di_octavio_ocampoLe illusioni di_octavio_ocampo
Le illusioni di_octavio_ocampo
 
Media studies as_questionnaire_graphed_results
Media studies as_questionnaire_graphed_resultsMedia studies as_questionnaire_graphed_results
Media studies as_questionnaire_graphed_results
 
Ekonomi
EkonomiEkonomi
Ekonomi
 
Edu
EduEdu
Edu
 
Evaluation question 2
Evaluation question 2Evaluation question 2
Evaluation question 2
 
mitad del mundo by tania leon
mitad del mundo by tania leonmitad del mundo by tania leon
mitad del mundo by tania leon
 
ИС на вашей работе
ИС на вашей работеИС на вашей работе
ИС на вашей работе
 
natural reserves in ecuador by tania leon
natural reserves in ecuador by tania leonnatural reserves in ecuador by tania leon
natural reserves in ecuador by tania leon
 
Acelgas
AcelgasAcelgas
Acelgas
 
Изображения в ИТ
Изображения в ИТ Изображения в ИТ
Изображения в ИТ
 
001المدونات
 001المدونات 001المدونات
001المدونات
 
Sazooinfo
SazooinfoSazooinfo
Sazooinfo
 
Oficina Arduino - Jornada de Tecnologia 2014 (E-poti) - Part II
Oficina Arduino - Jornada de Tecnologia 2014 (E-poti) - Part IIOficina Arduino - Jornada de Tecnologia 2014 (E-poti) - Part II
Oficina Arduino - Jornada de Tecnologia 2014 (E-poti) - Part II
 
Storyboards Final Draft
Storyboards Final DraftStoryboards Final Draft
Storyboards Final Draft
 
The short film context part 6
The short film context part 6The short film context part 6
The short film context part 6
 
Materi Fungsi/Pemetaan oleh Yudi Prasetyo, S.Pd
Materi Fungsi/Pemetaan oleh Yudi Prasetyo, S.PdMateri Fungsi/Pemetaan oleh Yudi Prasetyo, S.Pd
Materi Fungsi/Pemetaan oleh Yudi Prasetyo, S.Pd
 
InfoPI 2013 - Minicurso - Introdução ao CUDA - Segunda Parte
InfoPI 2013 - Minicurso - Introdução ao CUDA - Segunda ParteInfoPI 2013 - Minicurso - Introdução ao CUDA - Segunda Parte
InfoPI 2013 - Minicurso - Introdução ao CUDA - Segunda Parte
 

Similar to Lesson2

Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_reviewEdureka!
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptxssuserb1a18d
 
demo1 java of demo 1 java with demo 1 java.ppt
demo1 java of demo 1 java with demo 1 java.pptdemo1 java of demo 1 java with demo 1 java.ppt
demo1 java of demo 1 java with demo 1 java.pptFerdieBalang
 
NSCoder Swift - An Introduction to Swift
NSCoder Swift - An Introduction to SwiftNSCoder Swift - An Introduction to Swift
NSCoder Swift - An Introduction to SwiftAndreas Blick
 
Learning core java
Learning core javaLearning core java
Learning core javaAbhay Bharti
 
01 Java Language And OOP PART I
01 Java Language And OOP PART I01 Java Language And OOP PART I
01 Java Language And OOP PART IHari Christian
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
First Class Variables as AST Annotations
 First Class Variables as AST Annotations First Class Variables as AST Annotations
First Class Variables as AST AnnotationsESUG
 

Similar to Lesson2 (20)

Android webinar class_java_review
Android webinar class_java_reviewAndroid webinar class_java_review
Android webinar class_java_review
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptx
 
Lesson3
Lesson3Lesson3
Lesson3
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java
JavaJava
Java
 
demo1 java of demo 1 java with demo 1 java.ppt
demo1 java of demo 1 java with demo 1 java.pptdemo1 java of demo 1 java with demo 1 java.ppt
demo1 java of demo 1 java with demo 1 java.ppt
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Java Unit 2(Part 1)
Java Unit 2(Part 1)Java Unit 2(Part 1)
Java Unit 2(Part 1)
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
ITFT - Java
ITFT - JavaITFT - Java
ITFT - Java
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
NSCoder Swift - An Introduction to Swift
NSCoder Swift - An Introduction to SwiftNSCoder Swift - An Introduction to Swift
NSCoder Swift - An Introduction to Swift
 
Java
Java Java
Java
 
Learning core java
Learning core javaLearning core java
Learning core java
 
Java tutorial part 3
Java tutorial part 3Java tutorial part 3
Java tutorial part 3
 
01 Java Language And OOP PART I
01 Java Language And OOP PART I01 Java Language And OOP PART I
01 Java Language And OOP PART I
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
First Class Variables as AST Annotations
 First Class Variables as AST Annotations First Class Variables as AST Annotations
First Class Variables as AST Annotations
 

Recently uploaded

Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Recently uploaded (20)

Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

Lesson2

  • 1. Introduction to Java 2 Programming Lecture 2 Java Syntax
  • 2. Overview • Java Syntax – The Basics – Classes, Packages
  • 3. Naming • All Java syntax is case sensitive • Valid Java names – Consist of letters, numbers, underscore, and dollar – Names can only start with letter or underscore – E.g. firstAttribute but not 1stAttribute • “Camel case” convention – Java encourages long, explanatory names – Start with a lower case letter, with words capitalised – E.g. thisIsCamelCase, andSoIsThisAsWell
  • 4. Java Types • Java has two basic types – Primitive types – Reference Types • Primitive types – integers, floating point numbers, characters, etc – Refer to actual values • Reference types – Arrays, Classes, Objects, etc – Refer to memory locations (by name, not location)
  • 5. Primitive Types Type Description Size Boolean (boolean) True/false value 1 bit Byte (byte) Byte-length integer 1 byte Short (short) Short integer 2 bytes Integer (int) Integer 4 bytes Long (long) Long Integer 8 bytes Float (float) Single precision floating 4 bytes point number Double (double) Double precision float 8 bytes Char (char) Single character 2 bytes
  • 6. Syntax Examples (Variables) int anInteger; Boolean isSwitchOn; Variables can be initialised when they are declared Int anInteger = 10; Boolean isSwitchOn = true;
  • 7. Syntax Examples (if) if (x == y) { //executes if true } if (somethingIsTrue()) { doSomething(); } else { doSomethingElse(); }
  • 8. Example (for) int x=0; for (int i=1; i<=10; i++) { //code to repeat ten times x = x + i; }
  • 9. Example (while) int x=0; while (x < 10) { doSomething(); x++; } //loop forever while (true) { }
  • 10. Methods • Define some behaviour of a class • Method declarations have four basic sections, and a method body: – Visibility modifier (who can call the method) – Return type (what does it return) – Method name – Parameter list (what parameters does it accept)
  • 11. Syntax Examples (Methods) public void calculatePayroll() { //code goes here } private int addNumbers(int x, int y) { //code goes here }
  • 12. Method Naming Conventions • If a method sets some value on an object public void setVatLevel(float vat); • If a method retrieves some value from the object public float getTotalPayroll(); • If a method returns a boolean value public boolean isSwitchOn();
  • 13. Classes • One Java class defined in each .java file • File name must match the name of the class – Otherwise there will be compilation errors – Class names start with an upper case letter • Compiler will generate a .class file with same name – Contains the bytecode • Classes defined using the class keyword.
  • 14. Packages • Group related classes together • Each class in a package must have a unique name • Indicate the package a class belongs to with the package keyword • Recommended each class is put in a package • Gain access to public classes in other packages using the import keyword – The JVM needs to know where the classes are defined before you can use them
  • 15. Anatomy of a Java Source File package intro2java; import java.util.*; /** * A description of the class */ public class MyFirstClass { //attributes private boolean isSomething; private int aCounter; //methods public void doSomething() { //code goes here } }
  • 16. Common Sources of Error • Mistakes in naming – Wrong case, illegal names – class name and source file name not the same • Missing semi-colon • Missing curly brackets • Incorrect Loop checks – Loop is too large/small, or occurs forever • Testing equality – Assignment with = (single equals sign) – Comparison with == (two equals signs)

Editor's Notes

  1. Meaningful names are an important way to make your code understandable. While the later examples don’t always follow that recommendation, that’s just to save space on the slides. Camel case is also recommended as it makes long identifier names much more readable. It’s called camel case because there are humps in the words! Note that there are naming conventions for method names and variables also (see later slides)
  2. Primitive types are basic values. References types are structures (arrays, classes, objects, etc). A reference is as close as Java gets to a C pointer, but references are accessed by name and not by location. A Java programmer has no control over memory allocations, locations, etc. Ideally in an OO language everything would be an object of some form, and Java does have objects that represent the kinds of values that can be stored in primitive types. However reference types take up more memory so for efficiency, Java allows values to be stored in a primitive form.
  3. Methods can also indicate what kinds of errors (exceptions) might arise when they’re called. We’ll cover these in a later section. Methods defined in interfaces don’t have a method body, again we’ll cover these later. There are also some additional types of modifiers (e.g. abstract, final) which we’ll also cover later!
  4. There’s no equivalent of the C/C++ header file: just the .java file. One class per file (some exceptions, but outside the scope of this course). File name matching the class name is important. File names are case sensitive, just as class names are.
  5. Classes declare that they belong to a package. There’s no way for a package to be defined separately. Packages are a way of grouping relating classes together, to build a modular unit. The basic Java API has a Large number of pages, e.g. java.lang for the basic, java.util for utility classes, java.net for networking, etc. If a class wishes to refer to a class defined in another package, it must declare that it needs access to that package. This is done using the import keyword. It’s the responsibility of the JVM to find the relevant package, and classes on disk.