SlideShare a Scribd company logo
Zachary Blair
April 10, 2012
   Intro to Java and the JVM
   Basic Types/Arrays
   Classes/Inheritance
   Nested Classes
   Exceptions
   Enums
   Autoboxing/unboxing
   Annotations
   Generics
   Originally developed by Sun for embedded
    devices, version 1.0 released in 1996




   James Gosling (Father of Java, Officer of the
    Order of Canada),  photo by Peter Campbell
   Intended as an alternative to C++ that is:
    ◦   Simpler
    ◦   Higher-level
    ◦   Multithreaded
    ◦   Dynamic
    ◦   Object-oriented
    ◦   Trivially portable (“Write Once, Run Everywhere”)

    ◦ No pointer arithmetic
    ◦ Automatic garbage collection
   Emulates a “virtual” CPU             Java Source
                                         Files (.java)


    Executes “bytecode”
                                                javac


    (each opcode is one byte            Java bytecode
    long) stored in ‘.class’             files (.class)

    files

   The same “bytecode” can      x86 Java            ARM Java
    run on any machine with       Virtual             Virtual
                               Machine (JVM)       Machine (JVM)
    a JVM implemented for it
   Not specific to the Java language. Other
    languages compile for the JVM:

    ◦   Groovy
    ◦   Clojure
    ◦   Jython
    ◦   JRuby
    ◦   Dozens of others…
   Similar to C:
    byte              ->   8 bits
    short             ->   16 bits
    int               ->   32 bits
    long              ->   64 bits
    float             ->   32 bits
    double            ->   64 bits
    char              ->   16 bits
    boolean
   Numeric types are always signed
   ‘char’ is a 16 bits instead of 8!
   No conversion between int and boolean as in C++.
    if(0) or while(1) are compile-time errors in Java.
Eight bytes walk into a bar.  The bartender
       asks, “Can I get you anything?”


“Yeah,” reply the bytes.  “Make us a double.”


            ** I didn’t come up with this joke, but it’s comedy Gold.
   Similar to C in syntax
    int[] numbers = new int[10];
    numbers[0] = 1000;
   Arrays are Objects with members and
    methods (member functions)!
    for (int i = 0; i < numbers.length; i++) {
         System.out.println(numbers[i]);
    }

   Trying to index past the end of an array
    results in ArrayIndexOutOfBoundsException
public class Vector2D
{
     public int x;
     public int y;
     public float magnitude()
     {
          return Math.sqrt(x * x + y * y);
     }
}
   Method implementations must be defined in the
    class body. No ‘.h’ files, just ‘.java’!
   Classes themselves can have access modifiers!
   Each ‘public’ class must reside in a ‘.java’ file of
    the same name (e.g. Vector2D.java).
public class Velocity extends Point2D
    {
         public boolean isTooFast()
         {
              return (magnitude() > 60);
         }
    }

   Uses ‘extends’ to specify a base class
   Only single inheritance is supported
   All inheritance equivalent to ‘public’ in C++
   All classes implicitly inherit from Object
public class OuterClass
    {
         public int var;
         class InnerClass
         {
              public void foo()
              {
                   System.out.println(var);
              }
         }
    }

   Non-static inner classes have access to the
    outer class’s members!
   Instantiated using ‘this.new’ instead of ‘new’.
public void foo()
         {
              class Point
              {
                   public int x;
                   public int y;
              }

              Point p = new Point();
         }


   You can even declare a class inside a method!
button.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    System.out.println(“The button was pressed”);
  }
}


   Defined and instantiated an anonymous
    class that implements an “ActionListener”
    interface, all in the parameter list to a method
    call!

   Used as Java’s alternative to function pointers
    in C for callbacks.
try {
       int a[] = new int[2];
       System.out.println(“A three:" + a[3]);
}
catch (ArrayIndexOutOfBoundsException e) {
     System.out.println("Exception:" + e);
}


    Handle error conditions, similar to C++’s try/catch.
    Some exceptions are ‘checked’, meaning it is a
     compile-time error to not either catch them, or
     explicitly mark your method as possibly throwing
     that exception to its caller.
public enum Color
{
     RED, ORANGE, YELLOW, GREEN, BLUE
}
…
Color c = Color.RED;

   Like C enums, but in Java, enum is a sort of
    class with enum values as static members.
   You can add data and methods to the enum!
Color c = Color.RED;
if (c.isWarmColor())
 System.out.println(c.toString());
int x = 10;
Integer y = new Integer(x);
Integer z = x;

int a = z;

list list = new List();
list.append(x);               // x converted to
Integer
  Automatically convert between primitive types
   (e.g. int, double, char) to their Object-based
   (boxed) types (e.g. Integer, Double, Character).
  Useful because boxed types can be stored in
   collection classes just like any other Object
public class Base
{
     public void foo() { }
}
…
public class Subtype extends Base
{
     @Override public void foo() { bar(); }
}

   @Override marks a method as explicitly
    overriding a base class method, triggering a
    compilation error if it doesn’t!
class<T> Pair
    {
         public T first;
         public T second;
    }

    Pair<int> p = new Pair<int>();
    p.first = 10;
    p.second = 20;

   A bit like templates in C++ (except that
    internally only one implementation is
    created).
   Java has some similar syntax to C++
   Rather than compiling to native code, it
    compiles to bytecode for the JVM to execute
   Java makes it more difficult to make certain
    mistakes (automatic garbage collection and
    no pointer arithmetic).

   Learn more at http://docs.oracle.com/javase/
Intro to Java for C++ Developers

More Related Content

What's hot (19)

PDF
JNA - Let's C what it's worth
Idan Sheinberg
 
PDF
Swift, a quick overview
Julian Król
 
ODP
C# and the Evolution of a Programming Language
Jacinto Limjap
 
PPTX
002. Introducere in type script
Dmitrii Stoian
 
PPTX
KafNafParserPy: a python library for parsing/creating KAF and NAF files
Rubén Izquierdo Beviá
 
PPTX
C++ vs C#
sudipv
 
PPT
Lecture 1
Soran University
 
PPTX
CLTL presentation: training an opinion mining system from KAF files using CRF
Rubén Izquierdo Beviá
 
PPTX
Type hints in python & mypy
Anirudh
 
PDF
D programming language
Jordan Open Source Association
 
PDF
Type Profiler: Ambitious Type Inference for Ruby 3
mametter
 
ODP
The D Programming Language - Why I love it!
ryutenchi
 
PDF
Functional Programming In Practice
Michiel Borkent
 
PPTX
Presentation 1st
Connex
 
KEY
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
PPTX
TypeScript
Oswald Campesato
 
PPTX
C++ first s lide
Sudhriti Gupta
 
PPTX
Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees
rasmuskl
 
PPT
Oscon keynote: Working hard to keep it simple
Martin Odersky
 
JNA - Let's C what it's worth
Idan Sheinberg
 
Swift, a quick overview
Julian Król
 
C# and the Evolution of a Programming Language
Jacinto Limjap
 
002. Introducere in type script
Dmitrii Stoian
 
KafNafParserPy: a python library for parsing/creating KAF and NAF files
Rubén Izquierdo Beviá
 
C++ vs C#
sudipv
 
Lecture 1
Soran University
 
CLTL presentation: training an opinion mining system from KAF files using CRF
Rubén Izquierdo Beviá
 
Type hints in python & mypy
Anirudh
 
D programming language
Jordan Open Source Association
 
Type Profiler: Ambitious Type Inference for Ruby 3
mametter
 
The D Programming Language - Why I love it!
ryutenchi
 
Functional Programming In Practice
Michiel Borkent
 
Presentation 1st
Connex
 
Scala: functional programming for the imperative mind
Sander Mak (@Sander_Mak)
 
TypeScript
Oswald Campesato
 
C++ first s lide
Sudhriti Gupta
 
Exploring C# DSLs: LINQ, Fluent Interfaces and Expression Trees
rasmuskl
 
Oscon keynote: Working hard to keep it simple
Martin Odersky
 

Similar to Intro to Java for C++ Developers (20)

PPT
core java
Vinodh Kumar
 
PPT
Learning Java 1 – Introduction
caswenson
 
PPTX
Java PPT
Dilip Kr. Jangir
 
PDF
Java for beginners
Saeid Zebardast
 
PPT
1- java
Krishna Sujeer
 
PPT
java-corporate-training-institute-in-mumbai
Unmesh Baile
 
PPT
java-corporate-training-institute-in-mumbai
vibrantuser
 
PPT
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
nagendrareddy104104
 
PPT
Java Simple Introduction in single course
binzbinz3
 
PPT
java01.ppt
Godwin585235
 
PPT
Java Tutorials
Woxa Technologies
 
PPTX
Java programmingjsjdjdjdjdjdjdjdjdiidiei
rajputtejaswa12
 
ODP
Synapseindia reviews.odp.
Tarunsingh198
 
PPTX
Java tutorial for beginners-tibacademy.in
TIB Academy
 
PPT
Java Fundamentals.pptJava Fundamentals.ppt
yatakonakiran2
 
PPT
Java
Manav Prasad
 
PPT
INTRODUCTION TO JAVA
Pintu Dasaundhi (Rahul)
 
PPTX
Java Programming - UNIT - 1, Basics OOPS, Differences
PradeepT42
 
PPT
JavaTutorials.ppt
Khizar40
 
core java
Vinodh Kumar
 
Learning Java 1 – Introduction
caswenson
 
Java for beginners
Saeid Zebardast
 
java-corporate-training-institute-in-mumbai
Unmesh Baile
 
java-corporate-training-institute-in-mumbai
vibrantuser
 
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
nagendrareddy104104
 
Java Simple Introduction in single course
binzbinz3
 
java01.ppt
Godwin585235
 
Java Tutorials
Woxa Technologies
 
Java programmingjsjdjdjdjdjdjdjdjdiidiei
rajputtejaswa12
 
Synapseindia reviews.odp.
Tarunsingh198
 
Java tutorial for beginners-tibacademy.in
TIB Academy
 
Java Fundamentals.pptJava Fundamentals.ppt
yatakonakiran2
 
INTRODUCTION TO JAVA
Pintu Dasaundhi (Rahul)
 
Java Programming - UNIT - 1, Basics OOPS, Differences
PradeepT42
 
JavaTutorials.ppt
Khizar40
 
Ad

Recently uploaded (20)

PDF
Governing Geospatial Data at Scale: Optimizing ArcGIS Online with FME in Envi...
Safe Software
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PDF
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
PDF
Next Generation AI: Anticipatory Intelligence, Forecasting Inflection Points ...
dleka294658677
 
PDF
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Governing Geospatial Data at Scale: Optimizing ArcGIS Online with FME in Envi...
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Pitch ...
Michele Kryston
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
Next Generation AI: Anticipatory Intelligence, Forecasting Inflection Points ...
dleka294658677
 
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Ad

Intro to Java for C++ Developers

  • 2. Intro to Java and the JVM  Basic Types/Arrays  Classes/Inheritance  Nested Classes  Exceptions  Enums  Autoboxing/unboxing  Annotations  Generics
  • 3. Originally developed by Sun for embedded devices, version 1.0 released in 1996  James Gosling (Father of Java, Officer of the Order of Canada), photo by Peter Campbell
  • 4. Intended as an alternative to C++ that is: ◦ Simpler ◦ Higher-level ◦ Multithreaded ◦ Dynamic ◦ Object-oriented ◦ Trivially portable (“Write Once, Run Everywhere”) ◦ No pointer arithmetic ◦ Automatic garbage collection
  • 5. Emulates a “virtual” CPU Java Source Files (.java) Executes “bytecode” javac  (each opcode is one byte Java bytecode long) stored in ‘.class’ files (.class) files  The same “bytecode” can x86 Java ARM Java run on any machine with Virtual Virtual Machine (JVM) Machine (JVM) a JVM implemented for it
  • 6. Not specific to the Java language. Other languages compile for the JVM: ◦ Groovy ◦ Clojure ◦ Jython ◦ JRuby ◦ Dozens of others…
  • 7. Similar to C: byte -> 8 bits short -> 16 bits int -> 32 bits long -> 64 bits float -> 32 bits double -> 64 bits char -> 16 bits boolean  Numeric types are always signed  ‘char’ is a 16 bits instead of 8!  No conversion between int and boolean as in C++. if(0) or while(1) are compile-time errors in Java.
  • 8. Eight bytes walk into a bar.  The bartender asks, “Can I get you anything?” “Yeah,” reply the bytes.  “Make us a double.” ** I didn’t come up with this joke, but it’s comedy Gold.
  • 9. Similar to C in syntax int[] numbers = new int[10]; numbers[0] = 1000;  Arrays are Objects with members and methods (member functions)! for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }  Trying to index past the end of an array results in ArrayIndexOutOfBoundsException
  • 10. public class Vector2D { public int x; public int y; public float magnitude() { return Math.sqrt(x * x + y * y); } }  Method implementations must be defined in the class body. No ‘.h’ files, just ‘.java’!  Classes themselves can have access modifiers!  Each ‘public’ class must reside in a ‘.java’ file of the same name (e.g. Vector2D.java).
  • 11. public class Velocity extends Point2D { public boolean isTooFast() { return (magnitude() > 60); } }  Uses ‘extends’ to specify a base class  Only single inheritance is supported  All inheritance equivalent to ‘public’ in C++  All classes implicitly inherit from Object
  • 12. public class OuterClass { public int var; class InnerClass { public void foo() { System.out.println(var); } } }  Non-static inner classes have access to the outer class’s members!  Instantiated using ‘this.new’ instead of ‘new’.
  • 13. public void foo() { class Point { public int x; public int y; } Point p = new Point(); }  You can even declare a class inside a method!
  • 14. button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println(“The button was pressed”); } }  Defined and instantiated an anonymous class that implements an “ActionListener” interface, all in the parameter list to a method call!  Used as Java’s alternative to function pointers in C for callbacks.
  • 15. try { int a[] = new int[2]; System.out.println(“A three:" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception:" + e); }  Handle error conditions, similar to C++’s try/catch.  Some exceptions are ‘checked’, meaning it is a compile-time error to not either catch them, or explicitly mark your method as possibly throwing that exception to its caller.
  • 16. public enum Color { RED, ORANGE, YELLOW, GREEN, BLUE } … Color c = Color.RED;  Like C enums, but in Java, enum is a sort of class with enum values as static members.  You can add data and methods to the enum! Color c = Color.RED; if (c.isWarmColor()) System.out.println(c.toString());
  • 17. int x = 10; Integer y = new Integer(x); Integer z = x; int a = z; list list = new List(); list.append(x); // x converted to Integer  Automatically convert between primitive types (e.g. int, double, char) to their Object-based (boxed) types (e.g. Integer, Double, Character).  Useful because boxed types can be stored in collection classes just like any other Object
  • 18. public class Base { public void foo() { } } … public class Subtype extends Base { @Override public void foo() { bar(); } }  @Override marks a method as explicitly overriding a base class method, triggering a compilation error if it doesn’t!
  • 19. class<T> Pair { public T first; public T second; } Pair<int> p = new Pair<int>(); p.first = 10; p.second = 20;  A bit like templates in C++ (except that internally only one implementation is created).
  • 20. Java has some similar syntax to C++  Rather than compiling to native code, it compiles to bytecode for the JVM to execute  Java makes it more difficult to make certain mistakes (automatic garbage collection and no pointer arithmetic).  Learn more at http://docs.oracle.com/javase/