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
 

Similar to Lesson2

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
 
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
 

Recently uploaded

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
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
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
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
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
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
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
 
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
 

Recently uploaded (20)

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
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
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"
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
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
 
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
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
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
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
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
 
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
 

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.