SlideShare a Scribd company logo
Learning Java 1: Introduction Christopher Swenson Center for Information Security University of Tulsa 600 S. College Ave Tulsa, OK 74104
Learning Java Based on  Learning Java , by  Niemeyer and Knudsen Quick and Dirty overview of Java fundamentals and advanced  programming Introduction Objects and Classes Generics, Core Utilities Threads, Synchronization I/O, Network Programming Swing
Overview (Ch. 1–5) Java Hello World! Using Java Java Language Objects
Java Modern, Object-Oriented (OO) Language with C-like syntax Developed at Sun Microsystems (James Gosling, Bill Joy) in the early 1990s Virtual Machine Intermediate bytecode Extremely portable Surprisingly fast (comparable to C++) Features HotSpot on-the-fly native compiling Safe and Clean Dynamic Memory Management Robust Error Handling http://java.sun.com http://java.sun.com/j2se/1.5.0/docs/api/
Let’s Go! Standard CLI utilities, although IDEs and GUIs exist (Eclipse, Netbeans) Windows: Start    Run    “ cmd ” UNIX / OS X: Open up a command terminal “ javac HelloJava.java ” Compiles the file  HelloJava.java Outputs executable  .class  files
HelloJava.java public class HelloJava { public static void main(String[] args) { System.out.println(“Hello World!”); } } Run with: java -cp . HelloJava Outputs: Hello World!
Some Notes public class HelloJava  { … Everything in Java must be in a class (container for code and data). public static void main(String[] args){ … This is a method (which contains executable code). The function called from the command-line is required to be  main . Takes a  String  array (the arguments), and returns nothing ( void ). System.out.println(“Hello World!”); System  is a class that contains a lot of useful system-wide tools, like standard I/O, and its  out  class represents standard out. The  println  method of out (and all  PrintStream  objects) prints the  String  containted within, followed by a newline. java -cp . HelloJava Invokes the Java Virtual Machine (JVM) to execute the  main  of the named class ( HelloJava ). Searches the current directory for the class file ( -cp . ).
Comments /* */  C-style comments are also supported /** */  are special JavaDoc comments Allow automatic documentation to be built from source code, using the  javadoc  utility. //  C++-style comments are preferred Less ambiguity Simpler
Variables String s = “string”; int a = -14; long b = 5000000000l; float c = 2.5f; double d = -4.0d; byte e = 0x7f; char f = ‘c’; short g = -31000; boolean h = true; int s are signed 32-bit long s are signed 64-bit float s are signed 32-bit double s are signed 64-bit byte s are signed 8-bit char s are signed 16-bit short s are signed 16-bit boolean s are 1-bit, either  true  or  false
Operators Standard arithmetic operators for ints, longs, shorts, bytes, floats and doubles + - * / % << >> >>> Boolean operators for non-floating point & | ^ ~ Logical operators for  boolean s && || ^^ ~ Comparisons generate  boolean s == < <= > >= != Can be suffixed with  =  to indicate an assignment a = a + b      a += b ++   and   --   operators also ( a = a - 1      a-- ) Ternary Operator: (a >= b) ? c : d      if (a >= b) c else d
Reference Types Reference Types are non-primitive constructs Includes  String s Consist of variables and methods (code) Typically identified with capital letter Foo bar = new Foo(); Use the  new  keyword to explicitly construct new objects Can take arguments No need for destructor or to explicitly remove it No pointers C++:  Foo &bar  = *(new Foo());
String Strings are a reference type, but  almost  a primitive in Java String s = “this is a string”; No need for  new  construction Overloaded + operator for concatenation String s = “a” + “ kitten\n”;
Coercion Coercion = automatic conversion between types Up is easy ( int  to  double , anything to  String ) Down is hard int i = 2; double num = 3.14 * i; String s = “” + num; int a = Integer.parseInt(t);
Expressions and Statements An statement is a line of code to be evaluated a = b; An statement can be made compound using curly braces { a = b; c = d; } Curly braces also indicate a new scope (so can have its own local variables) Assignments can also be used as expressions (the value is the value of the variable after the assignment) a = (b = c);
if-then-else  statements if (bool) stmt1; if (bool) stmt1 else statement2; if (bool) stmt1 else if stmt2 else stmt3; if (bool) { stmt1; … ; } … if  (i == 100) System.out.println(i);
Do-while loops while (bool) stmt; do stmt; while (bool); boolean stop = false; while  (!stop) { // Stuff if (i == 100) stop = true; }
for  loops for  ( prestmt ;  bool ;  stepstmt ;)  stmt ; =  {  prestmt ; while ( bool ) {  stmt ;  stepstmt ; } } for (int i = 0; i < 10; i++) { System.out.print(i + “ “); } Outputs: “ 0 1 2 3 4 5 6 7 8 9   ”
switch  statement switch  ( int expression ) { case   int_constant :   stmt ; break ; case   int_constant :   stmt ; case   int_constant :   stmt ; default:   stmt ; }
Arrays int []  array =  { 1,2,3 } ; int []  array =  new int[ 10 ]; for (int i = 0; i <  array.length ; i++) array [ i ]  = i; Array indices are from 0 to (length – 1) Multi-dimensional arrays are actually arrays of arrays: int [][]  matrix = new int [3][3]; for (int i = 0; i <  matrix.length ; i++) for (int j = 0; j <  matrix[i].length ; j++) System.out.println(“Row: “ + i + “, Col: “ + j + “ = “ + matrix [i][j] );
enum s What about something, like size? Pre-Java 1.5,  int small = 1, medium = 2, … But what if  mySize == -14 ? enum  Size {Small, Medium, Large}; Can also do switch statements on enums switch (mySize) { case Small:  // … default:  // … }
Loop breaking break  breaks out of the current loop or switch statement while (!stop) { while (0 == 0) { break ; } // Execution continues here }
Loop continuing continue  goes back to the beginning of a loop boolean stop = false; int num = 0; while (!stop) { if (num < 100)  continue ; if (num % 3) stop = true; }
Objects class  Person { String name; int age; } Person me =  new  Person(); me.name = “Bill”; me.age = 34; Person[] students = new Person[50]; students[0] = new Person();
Subclassing class Professor  extends  Person { String office; } Professor bob = new Professor(); bob.name = “Bob”; bob.age = 40; bob.office = “U367”; However, a class can only “extend” one other class
Abstract Classes If not all of its methods are implemented (left abstract), a class is called abstract abstract  class Fish { abstract  void doesItEat(String food); public void swim() { // code for swimming } }
Interfaces class MyEvent  implements  ActionListener { public void actionPerformed(ActionEvent ae) { System.out.println(“My Action”); } } Can implement multiple interfaces Interfaces have abstract methods, but no normal variables
Static and final A  static  method or variable is tied to the class, NOT an instance of the class Something marked  final  cannot be overwritten (classes marked final cannot be subclassed) class Person { public  final static  int version = 2; static  long numberOfPeople = 6000000000; static void birth() { numberOfPeople++; } String name; int age; } // … in some other code Person.numberOfPeople++; System.out.println(“Running Version “ + Person.version + “ of Person class);
Special functions All classes extend the Object class Classes have built-in functions: equals(Object obj), hashCode(), toString() Equals used to determine if two objects are the same o == p  – checks their memory addresses o.equals(p)  – runs  o.equals() hashCode()  – used for hash tables ( int ) toString()  – used when cast as a  String  (like printing)
Packages Classes can be arranged into packages and subpackages, a hierarchy that Java uses to find class files Prevents naming issues Allows access control By default, a null package Doesn’t work well if you need more than a few classes, or other classes from other packages java.io  – Base I/O Package java.io.OutputStream  – full name Declare a package with a  package  keyword at the top Import stuff from package with the import keyword import java.io.*; import java.util.Vector; import static java.util.Arrays.sort;
Using Packages Compile like normal Packages = a directory Java has a “classpath”: root directories and archives where it expects to look for classes Example java -cp compiled swenson.MyServer In the the “compiled” directory, look for a class MyServer in the subfolder “swenson” /compiled/swenson/MyServer.class Also need to specify  -classpath  when compiling Class files can also be put into ZIP files (with a suffix of JAR instead of ZIP)
Permissions public  – accessible by anyone  protected  – accessible by anything in the package, or by subclasses (default) – accessible by anything in the package private  – accessible only by class
Coding Style class Test { public static void main(String[] args) { if (args.length > 0) System.out.println(“We have args!”); for (int i = 0; i < args.length; i++) { int q = Integer.parseInt(args[i]); System.out.println(2 * q); } System.exit(0); } }
Tools: Eclipse Popular Auto Complete Fancy Multi-language
Tools: NetBeans Another good GUI Full-featured Java-centric
Tools: JSwat Debugger
emacs
vi
TextPad
Homework Download Java Download a GUI and learn it (e.g., Eclipse) Implement a Card class enum s for Suit hashCode()  should return a different value for two different cards, but should be the same for two instances of the same card (e.g., Jack of Diamonds) Write a program that builds a deck and deals 5 cards to 4 different players toString()  should work so you can use System.out.println() to print out a deck, hand, or a card

More Related Content

PPT
Java tut1 Coderdojo Cahersiveen
PPTX
Unit testing concurrent code
PDF
Java Concurrency by Example
PPTX
The definitive guide to java agents
PPT
Java tut1
PPT
Tutorial java
PDF
Java Programming - 03 java control flow
PDF
Java Fundamentals
Java tut1 Coderdojo Cahersiveen
Unit testing concurrent code
Java Concurrency by Example
The definitive guide to java agents
Java tut1
Tutorial java
Java Programming - 03 java control flow
Java Fundamentals

What's hot (19)

PPTX
A topology of memory leaks on the JVM
PPTX
Java byte code in practice
PPT
Java tutorial for Beginners and Entry Level
PPTX
Making Java more dynamic: runtime code generation for the JVM
PPTX
An introduction to JVM performance
PPTX
Java 10, Java 11 and beyond
PPTX
Understanding Java byte code and the class file format
PPTX
Byte code field report
PPT
final year project center in Coimbatore
PDF
Object Oriented Programming in PHP
ODP
Synapseindia reviews.odp.
PPT
Java Tut1
PPT
Javatut1
PDF
Sam wd programs
PPTX
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
PPTX
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
PDF
Java programs
PPT
Presentation to java
A topology of memory leaks on the JVM
Java byte code in practice
Java tutorial for Beginners and Entry Level
Making Java more dynamic: runtime code generation for the JVM
An introduction to JVM performance
Java 10, Java 11 and beyond
Understanding Java byte code and the class file format
Byte code field report
final year project center in Coimbatore
Object Oriented Programming in PHP
Synapseindia reviews.odp.
Java Tut1
Javatut1
Sam wd programs
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Java programs
Presentation to java
Ad

Similar to Learning Java 1 – Introduction (20)

PPTX
Java introduction
PPT
Java Simple Introduction in single course
PPT
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
PPTX
Java programmingjsjdjdjdjdjdjdjdjdiidiei
PPT
java01.ppt
PPT
JAVA ppt tutorial basics to learn java programming
PPT
PPTX
Java tutorial for beginners-tibacademy.in
PPT
Present the syntax of Java Introduce the Java
PPT
java_ notes_for__________basic_level.ppt
PPT
java ppt for basic intro about java and its
PPT
Java - A parent language and powerdul for mobile apps.
PPT
Java intro
PPT
Java01
PPT
Java01
PPT
Java PPt.ppt
PPT
java-corporate-training-institute-in-mumbai
PPT
java-corporate-training-institute-in-mumbai
PPTX
mukul Dubey.pptx
PPT
java01.ppt
Java introduction
Java Simple Introduction in single course
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
Java programmingjsjdjdjdjdjdjdjdjdiidiei
java01.ppt
JAVA ppt tutorial basics to learn java programming
Java tutorial for beginners-tibacademy.in
Present the syntax of Java Introduce the Java
java_ notes_for__________basic_level.ppt
java ppt for basic intro about java and its
Java - A parent language and powerdul for mobile apps.
Java intro
Java01
Java01
Java PPt.ppt
java-corporate-training-institute-in-mumbai
java-corporate-training-institute-in-mumbai
mukul Dubey.pptx
java01.ppt
Ad

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation theory and applications.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Cloud computing and distributed systems.
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Approach and Philosophy of On baking technology
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation theory and applications.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Cloud computing and distributed systems.
Spectral efficient network and resource selection model in 5G networks
Encapsulation_ Review paper, used for researhc scholars
Approach and Philosophy of On baking technology
Digital-Transformation-Roadmap-for-Companies.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
20250228 LYD VKU AI Blended-Learning.pptx
NewMind AI Weekly Chronicles - August'25 Week I
Mobile App Security Testing_ A Comprehensive Guide.pdf
Electronic commerce courselecture one. Pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto

Learning Java 1 – Introduction

  • 1. Learning Java 1: Introduction Christopher Swenson Center for Information Security University of Tulsa 600 S. College Ave Tulsa, OK 74104
  • 2. Learning Java Based on Learning Java , by Niemeyer and Knudsen Quick and Dirty overview of Java fundamentals and advanced programming Introduction Objects and Classes Generics, Core Utilities Threads, Synchronization I/O, Network Programming Swing
  • 3. Overview (Ch. 1–5) Java Hello World! Using Java Java Language Objects
  • 4. Java Modern, Object-Oriented (OO) Language with C-like syntax Developed at Sun Microsystems (James Gosling, Bill Joy) in the early 1990s Virtual Machine Intermediate bytecode Extremely portable Surprisingly fast (comparable to C++) Features HotSpot on-the-fly native compiling Safe and Clean Dynamic Memory Management Robust Error Handling http://java.sun.com http://java.sun.com/j2se/1.5.0/docs/api/
  • 5. Let’s Go! Standard CLI utilities, although IDEs and GUIs exist (Eclipse, Netbeans) Windows: Start  Run  “ cmd ” UNIX / OS X: Open up a command terminal “ javac HelloJava.java ” Compiles the file HelloJava.java Outputs executable .class files
  • 6. HelloJava.java public class HelloJava { public static void main(String[] args) { System.out.println(“Hello World!”); } } Run with: java -cp . HelloJava Outputs: Hello World!
  • 7. Some Notes public class HelloJava { … Everything in Java must be in a class (container for code and data). public static void main(String[] args){ … This is a method (which contains executable code). The function called from the command-line is required to be main . Takes a String array (the arguments), and returns nothing ( void ). System.out.println(“Hello World!”); System is a class that contains a lot of useful system-wide tools, like standard I/O, and its out class represents standard out. The println method of out (and all PrintStream objects) prints the String containted within, followed by a newline. java -cp . HelloJava Invokes the Java Virtual Machine (JVM) to execute the main of the named class ( HelloJava ). Searches the current directory for the class file ( -cp . ).
  • 8. Comments /* */ C-style comments are also supported /** */ are special JavaDoc comments Allow automatic documentation to be built from source code, using the javadoc utility. // C++-style comments are preferred Less ambiguity Simpler
  • 9. Variables String s = “string”; int a = -14; long b = 5000000000l; float c = 2.5f; double d = -4.0d; byte e = 0x7f; char f = ‘c’; short g = -31000; boolean h = true; int s are signed 32-bit long s are signed 64-bit float s are signed 32-bit double s are signed 64-bit byte s are signed 8-bit char s are signed 16-bit short s are signed 16-bit boolean s are 1-bit, either true or false
  • 10. Operators Standard arithmetic operators for ints, longs, shorts, bytes, floats and doubles + - * / % << >> >>> Boolean operators for non-floating point & | ^ ~ Logical operators for boolean s && || ^^ ~ Comparisons generate boolean s == < <= > >= != Can be suffixed with = to indicate an assignment a = a + b  a += b ++ and -- operators also ( a = a - 1  a-- ) Ternary Operator: (a >= b) ? c : d  if (a >= b) c else d
  • 11. Reference Types Reference Types are non-primitive constructs Includes String s Consist of variables and methods (code) Typically identified with capital letter Foo bar = new Foo(); Use the new keyword to explicitly construct new objects Can take arguments No need for destructor or to explicitly remove it No pointers C++: Foo &bar = *(new Foo());
  • 12. String Strings are a reference type, but almost a primitive in Java String s = “this is a string”; No need for new construction Overloaded + operator for concatenation String s = “a” + “ kitten\n”;
  • 13. Coercion Coercion = automatic conversion between types Up is easy ( int to double , anything to String ) Down is hard int i = 2; double num = 3.14 * i; String s = “” + num; int a = Integer.parseInt(t);
  • 14. Expressions and Statements An statement is a line of code to be evaluated a = b; An statement can be made compound using curly braces { a = b; c = d; } Curly braces also indicate a new scope (so can have its own local variables) Assignments can also be used as expressions (the value is the value of the variable after the assignment) a = (b = c);
  • 15. if-then-else statements if (bool) stmt1; if (bool) stmt1 else statement2; if (bool) stmt1 else if stmt2 else stmt3; if (bool) { stmt1; … ; } … if (i == 100) System.out.println(i);
  • 16. Do-while loops while (bool) stmt; do stmt; while (bool); boolean stop = false; while (!stop) { // Stuff if (i == 100) stop = true; }
  • 17. for loops for ( prestmt ; bool ; stepstmt ;) stmt ; = { prestmt ; while ( bool ) { stmt ; stepstmt ; } } for (int i = 0; i < 10; i++) { System.out.print(i + “ “); } Outputs: “ 0 1 2 3 4 5 6 7 8 9 ”
  • 18. switch statement switch ( int expression ) { case int_constant : stmt ; break ; case int_constant : stmt ; case int_constant : stmt ; default: stmt ; }
  • 19. Arrays int [] array = { 1,2,3 } ; int [] array = new int[ 10 ]; for (int i = 0; i < array.length ; i++) array [ i ] = i; Array indices are from 0 to (length – 1) Multi-dimensional arrays are actually arrays of arrays: int [][] matrix = new int [3][3]; for (int i = 0; i < matrix.length ; i++) for (int j = 0; j < matrix[i].length ; j++) System.out.println(“Row: “ + i + “, Col: “ + j + “ = “ + matrix [i][j] );
  • 20. enum s What about something, like size? Pre-Java 1.5, int small = 1, medium = 2, … But what if mySize == -14 ? enum Size {Small, Medium, Large}; Can also do switch statements on enums switch (mySize) { case Small: // … default: // … }
  • 21. Loop breaking break breaks out of the current loop or switch statement while (!stop) { while (0 == 0) { break ; } // Execution continues here }
  • 22. Loop continuing continue goes back to the beginning of a loop boolean stop = false; int num = 0; while (!stop) { if (num < 100) continue ; if (num % 3) stop = true; }
  • 23. Objects class Person { String name; int age; } Person me = new Person(); me.name = “Bill”; me.age = 34; Person[] students = new Person[50]; students[0] = new Person();
  • 24. Subclassing class Professor extends Person { String office; } Professor bob = new Professor(); bob.name = “Bob”; bob.age = 40; bob.office = “U367”; However, a class can only “extend” one other class
  • 25. Abstract Classes If not all of its methods are implemented (left abstract), a class is called abstract abstract class Fish { abstract void doesItEat(String food); public void swim() { // code for swimming } }
  • 26. Interfaces class MyEvent implements ActionListener { public void actionPerformed(ActionEvent ae) { System.out.println(“My Action”); } } Can implement multiple interfaces Interfaces have abstract methods, but no normal variables
  • 27. Static and final A static method or variable is tied to the class, NOT an instance of the class Something marked final cannot be overwritten (classes marked final cannot be subclassed) class Person { public final static int version = 2; static long numberOfPeople = 6000000000; static void birth() { numberOfPeople++; } String name; int age; } // … in some other code Person.numberOfPeople++; System.out.println(“Running Version “ + Person.version + “ of Person class);
  • 28. Special functions All classes extend the Object class Classes have built-in functions: equals(Object obj), hashCode(), toString() Equals used to determine if two objects are the same o == p – checks their memory addresses o.equals(p) – runs o.equals() hashCode() – used for hash tables ( int ) toString() – used when cast as a String (like printing)
  • 29. Packages Classes can be arranged into packages and subpackages, a hierarchy that Java uses to find class files Prevents naming issues Allows access control By default, a null package Doesn’t work well if you need more than a few classes, or other classes from other packages java.io – Base I/O Package java.io.OutputStream – full name Declare a package with a package keyword at the top Import stuff from package with the import keyword import java.io.*; import java.util.Vector; import static java.util.Arrays.sort;
  • 30. Using Packages Compile like normal Packages = a directory Java has a “classpath”: root directories and archives where it expects to look for classes Example java -cp compiled swenson.MyServer In the the “compiled” directory, look for a class MyServer in the subfolder “swenson” /compiled/swenson/MyServer.class Also need to specify -classpath when compiling Class files can also be put into ZIP files (with a suffix of JAR instead of ZIP)
  • 31. Permissions public – accessible by anyone protected – accessible by anything in the package, or by subclasses (default) – accessible by anything in the package private – accessible only by class
  • 32. Coding Style class Test { public static void main(String[] args) { if (args.length > 0) System.out.println(“We have args!”); for (int i = 0; i < args.length; i++) { int q = Integer.parseInt(args[i]); System.out.println(2 * q); } System.exit(0); } }
  • 33. Tools: Eclipse Popular Auto Complete Fancy Multi-language
  • 34. Tools: NetBeans Another good GUI Full-featured Java-centric
  • 36. emacs
  • 37. vi
  • 39. Homework Download Java Download a GUI and learn it (e.g., Eclipse) Implement a Card class enum s for Suit hashCode() should return a different value for two different cards, but should be the same for two instances of the same card (e.g., Jack of Diamonds) Write a program that builds a deck and deals 5 cards to 4 different players toString() should work so you can use System.out.println() to print out a deck, hand, or a card