SlideShare a Scribd company logo
1 of 32
CMSC 341
Java Packages, Classes, Variables,
Expressions, Flow Control, and
Exceptions
8/3/2007 UMBC CMSC 341 Java 2 2
Sun’s Naming Conventions
 Classes and Interfaces
StringBuffer, Integer, MyDate
 Identifiers for methods, fields, and variables
_name, getName, setName, isName,
birthDate
 Packages
java.lang, java.util, proj1
 Constants
PI, MAX_NUMBER
8/3/2007 UMBC CMSC 341 Java 2 3
Comments
 Java supports three types of comments.
 C style /* multi-liner comments */
 C++ style // one liner comments
 Javadoc
/**
This is an example of a javadoc comment. These
comments can be converted to part of the pages you
see in the API.
*/
8/3/2007 UMBC CMSC 341 Java 2 4
The final modifier
 Constants in Java are created using the final
modifier.
final int MAX = 9;
 Final may also be applied to methods in which case
it means the method can not be overridden in
subclasses.
 Final may also be applied to classes in which case it
means the class can not be extended or subclassed
as in the String class.
8/3/2007 UMBC CMSC 341 Java 2 5
Packages
 Only one package per file.
 Packages serve as a namespace in Java and
create a directory hierarchy when compiled.
 Classes are placed in a package using the
following syntax in the first line that is not a
comment.
package packagename;
package packagename.subpackagename;
8/3/2007 UMBC CMSC 341 Java 2 6
Packages (cont.)
 Classes in a package are compiled using the
–d option.
 On the following slide, you will find the
command to compile the code from the
Proj1/src directory to the Proj1/bin
directory.
8/3/2007 UMBC CMSC 341 Java 2 7
Packages (cont.)
 It is common practice to duplicate the
package directory hierarchy in a directory
named src and to compile to a directory
named bin.
javac –d ../bin proj1/gui/Example.java
Proj1
proj1
proj1
src
bin
gui
gui
Example.java
Example.class
The following command is run from the src directory:
8/3/2007 UMBC CMSC 341 Java 2 8
Packages (cont.)
 By default, all classes that do not contain a package
declaration are in the unnamed package.
 The fully qualified name of a class is the
packageName.ClassName.
java.lang.String
 To alleviate the burden of using the fully qualified
name of a class, people use an import statement
found before the class declaration.
import java.util.StringBuffer;
import java.util.*;
8/3/2007 UMBC CMSC 341 Java 2 9
Fields and Methods
 In Java you have fields and methods. A field
is like a data member in C++.
 Method is like a member method in C++.
 Every field and method has an access level.
The public, private, and protected keywords
have the same functionality as those in C++.
 public
 protected
 private
 (package)
8/3/2007 UMBC CMSC 341 Java 2 10
Access Control
private
default
protected
public
Modifier Same class
Same
package
Subclass Universe
8/3/2007 UMBC CMSC 341 Java 2 11
Access Control for Classes
 Classes may have either public or package
accessibility.
 Only one public class per file.
 Omitting the access modifier prior to class
keyword gives the class package
accessibility.
8/3/2007 UMBC CMSC 341 Java 2 12
Classes
 In Java, all classes at some point in their
inheritance hierarchy are subclasses of
java.lang.Object, therefore all objects have
some inherited, default implementation
before you begin to code them.
 String toString()
 boolean equals(Object o)
8/3/2007 UMBC CMSC 341 Java 2 13
Classes (cont.)
 Unlike C++ you must define the accessibility
for every field and every method. In the
following code, the x is public but the y gets
the default accessibility of package since it
doesn’t have a modifier.
public
int x;
int y;
8/3/2007 UMBC CMSC 341 Java 2 14
Instance and Local Variables
 Unlike C++ you must define everything within
a class.
 Like C++,
 variables declared outside of method are instance
variables and store instance or object data. The
lifetime of the variable is the lifetime of the
instance.
 variables declared within a method, including the
parameter variables, are local variables. The
lifetime of the variable is the lifetime of the
method.
8/3/2007 UMBC CMSC 341 Java 2 15
Static Variables
 A class may also contain static variables and
methods.
 Similar to C++…
 Static variables store static or class data, meaning
only one copy of the data is shared by all objects
of the class.
 Static methods do not have access to instance
variables, but they do have access to static
variables.
 Instance methods also have access to static
variables.
8/3/2007 UMBC CMSC 341 Java 2 16
Instance vs. Static Methods
 Static methods
 have static as a modifier,
 can access static data,
 can be invoked by a host object or simply by using the
class name as a qualifier.
 Instance methods
 can access static data,
 can access instance data of the host object,
 must be invoked by a host object,
 contain a this reference that stores the address of host
object.
8/3/2007 UMBC CMSC 341 Java 2 17
Pass By Value or By Reference?
 All arguments are passed by value to a
method. However, since references are
addresses, in reality, they are passed by
reference, meaning…
 Arguments that contain primitive data are passed
by value. Changes to parameters in method do
not effect arguments.
 Arguments that contain reference data are passed
by reference. Changes to parameter in method
may effect arguments.
8/3/2007 UMBC CMSC 341 Java 2 18
Constructors
 Similar to C++, Java will provide a default (no
argument) constructor if one is not defined in
the class.
 Java, however, will initialize all fields (object
or instance data) to their zero values as in the
array objects.
 Like C++, once any constructor is defined,
the default constructor is lost unless explicitly
defined in the class.
8/3/2007 UMBC CMSC 341 Java 2 19
Constructors (cont.)
 Similar to C++, constructors in Java
 have no return value,
 have the same name as the class,
 initialize the data,
 and are typically overloaded.
 Unlike C++, a Java constructor can call
another constructor using a call to a this
method as the first line of code in the
constructor.
8/3/2007 UMBC CMSC 341 Java 2 20
Expressions and Control Flow
 Java uses the same operators as C++. Only
differences are
 + sign can be used for String concatenation,
 logical and relative operators return a boolean.
 Same control flow constructs as C++, but
expression must return a boolean.
 Conditional
 if(<boolean expression>){…}else if(<boolean
expression>){…}else{…}
 switch(variable){case 1: …break; default:…}
 Variable must be an integral primitive type of size int or smaller, or
a char
8/3/2007 UMBC CMSC 341 Java 2 21
Control Flow Constructs (cont.)
 Iterative
 while (<boolean expression>) { … }
 do { … } while (<boolean expression>);
 for( <initialize>; <boolean expression>;
<update>) { … }
 break and continue work in the same way as
in C++.
 May use labels with break and continue as in
C++.
8/3/2007 UMBC CMSC 341 Java 2 22
Control Flow Constructs (cont.)
 Enhanced for loop since Java 5 for iterating over arrays and collections.
public class EnhancedLoop
{
public static void main(String []a )
{
Integer [] array = {new Integer(5),6,7,8,9};
for (int element: array){
element+= 10;
System.out.println(element);
}
for (int element: array){
System.out.println(element);
}
}
}
element is a local variable
8/3/2007 UMBC CMSC 341 Java 2 23
Example Class
public class Person
{
// instance data
private String name;
private int age = 21;
private static int drivingAge = 16;
private static int num = 0;
//constructors
public Person(String name)
{
this.name = name;
num++;
}
public Person(String name, int age){
this(name);
this.age = age;
}
static num tracks the
number of Person objects
Call to previous constructor
C++ style comments
8/3/2007 UMBC CMSC 341 Java 2 24
Example Class (cont.)
//accessor and mutators
public String getName(){
return name;
}
public void setName(int name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
The this
reference is
used to
differentiate
between
local and
instance
data
8/3/2007 UMBC CMSC 341 Java 2 25
Example Class (cont.)
/* static accessor methods
The this reference does not
exist in static methods
*/
public static int getDrivingAge(){
return drivingAge;
}
public static int getNum(){
return num;
}
C style comments
8/3/2007 UMBC CMSC 341 Java 2 26
Example Class (cont.)
//overridden methods inherited from Object
public String toString(){
return “Person “ + name;
}
public boolean equals(Object o){
if( o == null)
return false;
if( getClass() != o.getClass())
return false;
Person p = (Person)o;
return this.age == p.age;
}
}
Testing if Object
is a Person
Casting Object
to a Person
End of class…
no semicolon
8/3/2007 UMBC CMSC 341 Java 2 27
Example Driver Program
public class PersonTest
{
public static void main(String args[])
{
Person p = new Person(“Sally”);
Person p2 = new Person(“Jane”);
Person p3 = new Person(“Mike”);
p3.setAge(25);
PersonTest.compare(p, p2);
compare(p2,p3);
}
public static void compare(Person p1, Person p2)
{
System.out.println(p1 + “ is “ +
(p1.equals(p2)? “”: “not”) +
“ the same age as “ + p2);
}
}
p
p2
p2
Sally
21
Mike
21
Jane
21
Mike
XX
25
p1
p2
8/3/2007 UMBC CMSC 341 Java 2 28
Exceptions
 Java handles exceptions like C++.
 Place try block around problem code and a catch block
immediately following try block to handle exceptions.
 Different from C++…
 Java uses a finally block for code that is to be executed
whether or not an exception is thrown.
 Java has a built-in inheritance hierarchy for its exception
classes which determines whether an exception is a
checked or an unchecked exception.
 You may declare that a method throws an exception to
handle it. The exception is then passed up the call stack.
 Java forces the programmer to handle a checked exception
at compile time.
8/3/2007 UMBC CMSC 341 Java 2 29
Exception Hierarchy
 Unchecked exceptions are derived from
RuntimeException. Checked exceptions are
derived from Exception. Error are also
unchecked exceptions, but may not derive
from it. Throwable
Exception
Error
IOException RuntimeException
unchecked
unchecked
checked
checked
8/3/2007 UMBC CMSC 341 Java 2 30
Handling the Exception Example
public class HandleExample
{
public static void main(String args[])
{
try {
String name = args[0];
System.out.println(args[0]);
} catch (IndexOutOfBoundsException e){
System.out.println(“Please enter name ” +
“after java HandleExample”);
} finally {
System.out.println(“Prints no matter what”);
}
}
}
8/3/2007 UMBC CMSC 341 Java 2 31
Passing up the Exception
 In Java you may pass the handling of the exception
up the calling stack by declaring that the method
throws the exception using the keyword throws.
 This is necessary for compilation if you call a
method that throws a checked exception such as
the Thread.sleep method.
 The Java API lists the exceptions that a method may
throw. You may see the inheritance hierarchy of an
exception in the API to determine if it is checked or
unchecked.
8/3/2007 UMBC CMSC 341 Java 2 32
Passing up the Exception Example
public class PassUpExample
{
public static void main(String [] args){
System.out.println(“Hello”);
try
{
passback();
}catch(InterruptedException e)
{
System.out.println(“Caught InterruptedException”);
}
System.out.println(“Goodbye”);
}
public static void passback() throws InterruptedException
{
Thread.sleep(3000);
}
}
This method throws
a checked exception
This method passes
exception up call stack
main is obligated to handle
the exception since it is a
checked exception

More Related Content

Similar to Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)

Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorialBui Kiet
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Java Basics
Java BasicsJava Basics
Java BasicsF K
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfArthyR3
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxingGeetha Manohar
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorialrajkamaltibacademy
 
Java quick reference
Java quick referenceJava quick reference
Java quick referenceArthyR3
 

Similar to Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION) (20)

Java basic
Java basicJava basic
Java basic
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
OOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdfOOPs - JAVA Quick Reference.pdf
OOPs - JAVA Quick Reference.pdf
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 
Java mcq
Java mcqJava mcq
Java mcq
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 

Recently uploaded

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Recently uploaded (20)

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)

  • 1. CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions
  • 2. 8/3/2007 UMBC CMSC 341 Java 2 2 Sun’s Naming Conventions  Classes and Interfaces StringBuffer, Integer, MyDate  Identifiers for methods, fields, and variables _name, getName, setName, isName, birthDate  Packages java.lang, java.util, proj1  Constants PI, MAX_NUMBER
  • 3. 8/3/2007 UMBC CMSC 341 Java 2 3 Comments  Java supports three types of comments.  C style /* multi-liner comments */  C++ style // one liner comments  Javadoc /** This is an example of a javadoc comment. These comments can be converted to part of the pages you see in the API. */
  • 4. 8/3/2007 UMBC CMSC 341 Java 2 4 The final modifier  Constants in Java are created using the final modifier. final int MAX = 9;  Final may also be applied to methods in which case it means the method can not be overridden in subclasses.  Final may also be applied to classes in which case it means the class can not be extended or subclassed as in the String class.
  • 5. 8/3/2007 UMBC CMSC 341 Java 2 5 Packages  Only one package per file.  Packages serve as a namespace in Java and create a directory hierarchy when compiled.  Classes are placed in a package using the following syntax in the first line that is not a comment. package packagename; package packagename.subpackagename;
  • 6. 8/3/2007 UMBC CMSC 341 Java 2 6 Packages (cont.)  Classes in a package are compiled using the –d option.  On the following slide, you will find the command to compile the code from the Proj1/src directory to the Proj1/bin directory.
  • 7. 8/3/2007 UMBC CMSC 341 Java 2 7 Packages (cont.)  It is common practice to duplicate the package directory hierarchy in a directory named src and to compile to a directory named bin. javac –d ../bin proj1/gui/Example.java Proj1 proj1 proj1 src bin gui gui Example.java Example.class The following command is run from the src directory:
  • 8. 8/3/2007 UMBC CMSC 341 Java 2 8 Packages (cont.)  By default, all classes that do not contain a package declaration are in the unnamed package.  The fully qualified name of a class is the packageName.ClassName. java.lang.String  To alleviate the burden of using the fully qualified name of a class, people use an import statement found before the class declaration. import java.util.StringBuffer; import java.util.*;
  • 9. 8/3/2007 UMBC CMSC 341 Java 2 9 Fields and Methods  In Java you have fields and methods. A field is like a data member in C++.  Method is like a member method in C++.  Every field and method has an access level. The public, private, and protected keywords have the same functionality as those in C++.  public  protected  private  (package)
  • 10. 8/3/2007 UMBC CMSC 341 Java 2 10 Access Control private default protected public Modifier Same class Same package Subclass Universe
  • 11. 8/3/2007 UMBC CMSC 341 Java 2 11 Access Control for Classes  Classes may have either public or package accessibility.  Only one public class per file.  Omitting the access modifier prior to class keyword gives the class package accessibility.
  • 12. 8/3/2007 UMBC CMSC 341 Java 2 12 Classes  In Java, all classes at some point in their inheritance hierarchy are subclasses of java.lang.Object, therefore all objects have some inherited, default implementation before you begin to code them.  String toString()  boolean equals(Object o)
  • 13. 8/3/2007 UMBC CMSC 341 Java 2 13 Classes (cont.)  Unlike C++ you must define the accessibility for every field and every method. In the following code, the x is public but the y gets the default accessibility of package since it doesn’t have a modifier. public int x; int y;
  • 14. 8/3/2007 UMBC CMSC 341 Java 2 14 Instance and Local Variables  Unlike C++ you must define everything within a class.  Like C++,  variables declared outside of method are instance variables and store instance or object data. The lifetime of the variable is the lifetime of the instance.  variables declared within a method, including the parameter variables, are local variables. The lifetime of the variable is the lifetime of the method.
  • 15. 8/3/2007 UMBC CMSC 341 Java 2 15 Static Variables  A class may also contain static variables and methods.  Similar to C++…  Static variables store static or class data, meaning only one copy of the data is shared by all objects of the class.  Static methods do not have access to instance variables, but they do have access to static variables.  Instance methods also have access to static variables.
  • 16. 8/3/2007 UMBC CMSC 341 Java 2 16 Instance vs. Static Methods  Static methods  have static as a modifier,  can access static data,  can be invoked by a host object or simply by using the class name as a qualifier.  Instance methods  can access static data,  can access instance data of the host object,  must be invoked by a host object,  contain a this reference that stores the address of host object.
  • 17. 8/3/2007 UMBC CMSC 341 Java 2 17 Pass By Value or By Reference?  All arguments are passed by value to a method. However, since references are addresses, in reality, they are passed by reference, meaning…  Arguments that contain primitive data are passed by value. Changes to parameters in method do not effect arguments.  Arguments that contain reference data are passed by reference. Changes to parameter in method may effect arguments.
  • 18. 8/3/2007 UMBC CMSC 341 Java 2 18 Constructors  Similar to C++, Java will provide a default (no argument) constructor if one is not defined in the class.  Java, however, will initialize all fields (object or instance data) to their zero values as in the array objects.  Like C++, once any constructor is defined, the default constructor is lost unless explicitly defined in the class.
  • 19. 8/3/2007 UMBC CMSC 341 Java 2 19 Constructors (cont.)  Similar to C++, constructors in Java  have no return value,  have the same name as the class,  initialize the data,  and are typically overloaded.  Unlike C++, a Java constructor can call another constructor using a call to a this method as the first line of code in the constructor.
  • 20. 8/3/2007 UMBC CMSC 341 Java 2 20 Expressions and Control Flow  Java uses the same operators as C++. Only differences are  + sign can be used for String concatenation,  logical and relative operators return a boolean.  Same control flow constructs as C++, but expression must return a boolean.  Conditional  if(<boolean expression>){…}else if(<boolean expression>){…}else{…}  switch(variable){case 1: …break; default:…}  Variable must be an integral primitive type of size int or smaller, or a char
  • 21. 8/3/2007 UMBC CMSC 341 Java 2 21 Control Flow Constructs (cont.)  Iterative  while (<boolean expression>) { … }  do { … } while (<boolean expression>);  for( <initialize>; <boolean expression>; <update>) { … }  break and continue work in the same way as in C++.  May use labels with break and continue as in C++.
  • 22. 8/3/2007 UMBC CMSC 341 Java 2 22 Control Flow Constructs (cont.)  Enhanced for loop since Java 5 for iterating over arrays and collections. public class EnhancedLoop { public static void main(String []a ) { Integer [] array = {new Integer(5),6,7,8,9}; for (int element: array){ element+= 10; System.out.println(element); } for (int element: array){ System.out.println(element); } } } element is a local variable
  • 23. 8/3/2007 UMBC CMSC 341 Java 2 23 Example Class public class Person { // instance data private String name; private int age = 21; private static int drivingAge = 16; private static int num = 0; //constructors public Person(String name) { this.name = name; num++; } public Person(String name, int age){ this(name); this.age = age; } static num tracks the number of Person objects Call to previous constructor C++ style comments
  • 24. 8/3/2007 UMBC CMSC 341 Java 2 24 Example Class (cont.) //accessor and mutators public String getName(){ return name; } public void setName(int name){ this.name = name; } public int getAge(){ return age; } public void setAge(int age){ this.age = age; } The this reference is used to differentiate between local and instance data
  • 25. 8/3/2007 UMBC CMSC 341 Java 2 25 Example Class (cont.) /* static accessor methods The this reference does not exist in static methods */ public static int getDrivingAge(){ return drivingAge; } public static int getNum(){ return num; } C style comments
  • 26. 8/3/2007 UMBC CMSC 341 Java 2 26 Example Class (cont.) //overridden methods inherited from Object public String toString(){ return “Person “ + name; } public boolean equals(Object o){ if( o == null) return false; if( getClass() != o.getClass()) return false; Person p = (Person)o; return this.age == p.age; } } Testing if Object is a Person Casting Object to a Person End of class… no semicolon
  • 27. 8/3/2007 UMBC CMSC 341 Java 2 27 Example Driver Program public class PersonTest { public static void main(String args[]) { Person p = new Person(“Sally”); Person p2 = new Person(“Jane”); Person p3 = new Person(“Mike”); p3.setAge(25); PersonTest.compare(p, p2); compare(p2,p3); } public static void compare(Person p1, Person p2) { System.out.println(p1 + “ is “ + (p1.equals(p2)? “”: “not”) + “ the same age as “ + p2); } } p p2 p2 Sally 21 Mike 21 Jane 21 Mike XX 25 p1 p2
  • 28. 8/3/2007 UMBC CMSC 341 Java 2 28 Exceptions  Java handles exceptions like C++.  Place try block around problem code and a catch block immediately following try block to handle exceptions.  Different from C++…  Java uses a finally block for code that is to be executed whether or not an exception is thrown.  Java has a built-in inheritance hierarchy for its exception classes which determines whether an exception is a checked or an unchecked exception.  You may declare that a method throws an exception to handle it. The exception is then passed up the call stack.  Java forces the programmer to handle a checked exception at compile time.
  • 29. 8/3/2007 UMBC CMSC 341 Java 2 29 Exception Hierarchy  Unchecked exceptions are derived from RuntimeException. Checked exceptions are derived from Exception. Error are also unchecked exceptions, but may not derive from it. Throwable Exception Error IOException RuntimeException unchecked unchecked checked checked
  • 30. 8/3/2007 UMBC CMSC 341 Java 2 30 Handling the Exception Example public class HandleExample { public static void main(String args[]) { try { String name = args[0]; System.out.println(args[0]); } catch (IndexOutOfBoundsException e){ System.out.println(“Please enter name ” + “after java HandleExample”); } finally { System.out.println(“Prints no matter what”); } } }
  • 31. 8/3/2007 UMBC CMSC 341 Java 2 31 Passing up the Exception  In Java you may pass the handling of the exception up the calling stack by declaring that the method throws the exception using the keyword throws.  This is necessary for compilation if you call a method that throws a checked exception such as the Thread.sleep method.  The Java API lists the exceptions that a method may throw. You may see the inheritance hierarchy of an exception in the API to determine if it is checked or unchecked.
  • 32. 8/3/2007 UMBC CMSC 341 Java 2 32 Passing up the Exception Example public class PassUpExample { public static void main(String [] args){ System.out.println(“Hello”); try { passback(); }catch(InterruptedException e) { System.out.println(“Caught InterruptedException”); } System.out.println(“Goodbye”); } public static void passback() throws InterruptedException { Thread.sleep(3000); } } This method throws a checked exception This method passes exception up call stack main is obligated to handle the exception since it is a checked exception