SlideShare ist ein Scribd-Unternehmen logo
1 von 29
UMBC CMSC 331 Java
JAVA BASICSJAVA BASICS
Presented ByPresented By
KhasimKhasim
UMBC CMSC 331 Java
Comments are almost like C++Comments are almost like C++
The javadoc program generates HTML API
documentation from the “javadoc” style
comments in your code.
2
/* This kind of comment can span multiple lines */
// This kind is to the end of the line
/**
* This kind of comment is a special
* ‘javadoc’ style comment
*/
UMBC CMSC 331 Java
An example of a classAn example of a class
3
class Person {
String name;
int age;
void birthday ( ) {
age++;
System.out.println (name +
' is now ' + age);
}
}
Variable
Method
UMBC CMSC 331 Java
ScopingScoping
 As in C/C++, scope is determined by the placement of curly braces {}.
 A variable defined within a scope is available only to the end of that
scope.
4
{ int x = 12;
/* only x available */
{ int q = 96;
/* both x and q available */
}
/* only x available */
/* q “out of scope” */
}
{ int x = 12;
{ int x = 96; /* illegal */
}
}
This is ok in C/C++ but not in Java.
UMBC CMSC 331 Java
An array is an objectAn array is an object
 Person mary = new Person ( );
 int myArray[ ] = new int[5];
 int myArray[ ] = {1, 4, 9, 16, 25};
 String languages [ ] = {"Prolog",
"Java"};
 Since arrays are objects they are allocated dynamically
 Arrays, like all objects, are subject to garbage collection
when no more references remain
◩ so fewer memory leaks
◩ Java doesn’t have pointers!
5
UMBC CMSC 331 Java
Scope of ObjectsScope of Objects
Java objects don’t have the same lifetimes
as primitives.
When you create a Java object using new,
it hangs around past the end of the scope.
Here, the scope of name s is delimited by
the {}s but the String object hangs around
until GC’d
{
String s = new String("a
string"); 6
UMBC CMSC 331 Java
Methods, arguments and return valuesMethods, arguments and return values
Java methods are like C/C++ functions. General case:
returnType methodName ( arg1, arg2, 
 argN) {
methodBody
}
The return keyword exits a method optionally with a value
int storage(String s) {return s.length() *
2;}
boolean flag() { return true; }
float naturalLogBase() { return 2.718f; }
void nothing() { return; }
void nothing2() {}
7
UMBC CMSC 331 Java
The static keywordThe static keyword
Java methods and variables can be declared
static
These exist independent of any object
This means that a Class’s
◩ static methods can be called even if no objects
of that class have been created and
◩ static data is “shared” by all instances (i.e., one
rvalue per class instead of one per instance
8
class StaticTest {static int i = 47;}
StaticTest st1 = new StaticTest();
StaticTest st2 = new StaticTest();
// st1.i == st2.I == 47
StaticTest.i++; // or st1.I++ or st2.I++
// st1.i == st2.I == 48
UMBC CMSC 331 Java
Array OperationsArray Operations
Subscripts always start at 0 as in C
Subscript checking is done automatically
Certain operations are defined on arrays
of objects, as for other classes
◩ e.g. myArray.length == 5
9
UMBC CMSC 331 Java
ExampleExample
ProgramsPrograms
Echo.javaEcho.java
C:UMBC331java>type echo.java
// This is the Echo example from the Sun tutorial
class echo {
public static void main(String args[]) {
for (int i=0; i < args.length; i++) {
System.out.println( args[i] );
}
}
}
C:UMBC331java>javac echo.java
C:UMBC331java>java echo this is pretty silly
this
is
pretty
silly
C:UMBC331java>
UMBC CMSC 331 Java
Factorial ExampleFactorial Example
/**
* This program computes the factorial of a number
*/
public class Factorial { // Define a class
public static void main(String[] args) { // The program starts here
int input = Integer.parseInt(args[0]); // Get the user's input
double result = factorial(input); // Compute the factorial
System.out.println(result); // Print out the result
} // The main() method ends here
public static double factorial(int x) { // This method computes x!
if (x < 0) // Check for bad input
return 0.0; // if bad, return 0
double fact = 1.0; // Begin with an initial value
while(x > 1) { // Loop until x equals 1
fact = fact * x; // multiply by x each time
x = x - 1; // and then decrement x
} // Jump back to the star of
loop
return fact; // Return the result 12
From Java in a Nutshell
UMBC CMSC 331 Java
JAVA ClassesJAVA Classes
 The class is the fundamental concept in JAVA (and other
OOPLs)
 A class describes some data object(s), and the operations
(or methods) that can be applied to those objects
 Every object and method in Java belongs to a class
 Classes have data (fields) and code (methods) and classes
(member classes or inner classes)
 Static methods and fields belong to the class itself
 Others belong to instances
13
UMBC CMSC 331 Java
ExampleExample
public class Circle {
// A class field
public static final double PI= 3.14159; // A useful constant
// A class method: just compute a value based on the arguments
public static double radiansToDegrees(double rads) {
return rads * 180 / PI;
}
// An instance field
public double r; // The radius of the circle
// Two methods which operate on the instance fields of an object
public double area() { // Compute the area of the
circle
return PI * r * r;
}
public double circumference() { // Compute the circumference of
the circle
return 2 * PI * r;
}
}
14
UMBC CMSC 331 Java
ConstructorsConstructors
Classes should define one or more methods to create or
construct instances of the class
Their name is the same as the class name
◩ note deviation from convention that methods begin with lower case
Constructors are differentiated by the number and types
of their arguments
◩ An example of overloading
If you don’t define a constructor, a default one will be
created.
Constructors automatically invoke the zero argument
constructor of their superclass when they begin (note that
this yields a recursive process!)
15
UMBC CMSC 331 Java
Constructor exampleConstructor example
public class Circle {
public static final double PI = 3.14159; // A constant
public double r; // instance field holds circle’s radius
// The constructor method: initialize the radius field
public Circle(double r) { this.r = r; }
// Constructor to use if no arguments
public Circle() { r = 1.0; }
// better: public Circle() { this(1.0); }
// The instance methods: compute values based on radius
public double circumference() { return 2 * PI * r; }
public double area() { return PI * r*r; }
}
16
this.r refers to the r
field of the class
This() refers to a
constructor for the class
UMBC CMSC 331 Java
Extending a classExtending a class
 Class hierarchies reflect subclass-superclass relations among
classes.
 One arranges classes in hierarchies:
◩ A class inherits instance variables and instance methods from all of its
superclasses. Tree -> BinaryTree -> BST
◩ You can specify only ONE superclass for any class.
 When a subclass-superclass chain contains multiple instance
methods with the same signature (name, arity, and argument
types), the one closest to the target instance in the subclass-
superclass chain is the one executed.
◩ All others are shadowed/overridden.
 Something like multiple inheritance can be done via interfaces
(more on this later)
 What’s the superclass of a class defined without an extends
clause?
17
UMBC CMSC 331 Java
Extending a classExtending a class
public class PlaneCircle extends Circle {
// We automatically inherit the fields and methods of Circle,
// so we only have to put the new stuff here.
// New instance fields that store the center point of the circle
public double cx, cy;
// A new constructor method to initialize the new fields
// It uses a special syntax to invoke the Circle() constructor
public PlaneCircle(double r, double x, double y) {
super(r); // Invoke the constructor of the superclass, Circle()
this.cx = x; // Initialize the instance field cx
this.cy = y; // Initialize the instance field cy
}
// The area() and circumference() methods are inherited from Circle
// A new instance method that checks whether a point is inside the circle
// Note that it uses the inherited instance field r
public boolean isInside(double x, double y) {
double dx = x - cx, dy = y - cy; // Distance from center
double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem
return (distance < r); // Returns true or false 18
UMBC CMSC 331 Java
Overloading, overwriting, and shadowingOverloading, overwriting, and shadowing
 Overloading occurs when Java can distinguish two procedures
with the same name by examining the number or types of their
parameters.
 Shadowing or overriding occurs when two procedures with the
same signature (name, the same number of parameters, and the
same parameter types) are defined in different classes, one of
which is a superclass of the other.
19
UMBC CMSC 331 Java
On designing class hierarchiesOn designing class hierarchies
 Programs should obey the explicit-representation principle, with classes
included to reflect natural categories.
 Programs should obey the no-duplication principle, with instance methods
situated among class definitions to facilitate sharing.
 Programs should obey the look-it-up principle, with class definitions
including instance variables for stable, frequently requested information.
 Programs should obey the need-to-know principle, with public interfaces
designed to restrict instance-variable and instance-method access, thus
facilitating the improvement and maintenance of nonpublic program
elements.
 If you find yourself using the phrase an X is aY when describing the
relation between two classes, then the X class is a subclass of theY class.
 If you find yourself using X has aY when describing the relation between
two classes, then instances of theY class appear as parts of instances of
the X class.
20
UMBC CMSC 331 Java
Data hiding and encapsulationData hiding and encapsulation
Data-hiding or encapsulation is an
important part of the OO paradigm.
Classes should carefully control access to
their data and methods in order to
◩ Hide the irrelevant implementation-level details
so they can be easily changed
◩ Protect the class against accidental or malicious
damage.
◩ Keep the externally visible class simple and easy
to document
Java has a simple access control mechanism
to help with encapsulation 21
UMBC CMSC 331 Java
ExampleExample
encapsulationencapsulation
package shapes; // Specify a package for the class
public class Circle { // The class is still public
public static final double PI = 3.14159;
protected double r; // Radius is hidden, but visible to subclasses
// A method to enforce the restriction on the radius
// This is an implementation detail that may be of interest to subclasses
protected checkRadius(double radius) {
if (radius < 0.0)
throw new IllegalArgumentException("radius may not be negative.");
}
// The constructor method
public Circle(double r) {checkRadius(r); this.r = r; }
// Public data accessor methods
public double getRadius() { return r; };
public void setRadius(double r) { checkRadius(r); this.r = r;}
// Methods to operate on the instance field
public double area() { return PI * r * r; }
public double circumference() { return 2 * PI * r; }
}
22
UMBC CMSC 331 Java
Access controlAccess control
Access to packages
◩ Java offers no control mechanisms for packages.
◩ If you can find and read the package you can
access it
Access to classes
◩ All top level classes in package P are accessible
anywhere in P
◩ All public top-level classes in P are accessible
anywhere
Access to class members (in class C in
package P)
◩ Public: accessible anywhere C is accessible 23
24
UMBC CMSC 331 Java
Getters and settersGetters and setters
 A getter is a method that extracts information from an instance.
◩ One benefit: you can include additional computation in a getter.
 A setter is a method that inserts information into an instance (also
known as mutators).
◩ A setter method can check the validity of the new value (e.g., between 1
and 7) or trigger a side effect (e.g., update a display)
 Getters and setters can be used even without underlying matching
variables
 Considered good OO practice
 Essential to javabeans
 Convention: for variable fooBar of type fbtype, define
◩ getFooBar()
◩ setFooBar(fbtype x)
25
UMBC CMSC 331 Java
ExampleExample
getters and settersgetters and setters
package shapes; // Specify a package for the class
public class Circle { // The class is still public
// This is a generally useful constant, so we keep it public
public static final double PI = 3.14159;
protected double r; // Radius is hidden, but visible to subclasses
// A method to enforce the restriction on the radius
// This is an implementation detail that may be of interest to subclasses
protected checkRadius(double radius) {
if (radius < 0.0)
throw new IllegalArgumentException("radius may not be negative.");
}
// The constructor method
public Circle(double r) { checkRadius(r); this.r = r;}
// Public data accessor methods
public double getRadius() { return r; };
public void setRadius(double r) { checkRadius(r); this.r = r;}
// Methods to operate on the instance field
public double area() { return PI * r * r; }
public double circumference() { return 2 * PI * r; }
26
UMBC CMSC 331 Java
Abstract classes and methodsAbstract classes and methods
Abstract vs. concrete classes
Abstract classes can not be instantiated
public abstract class shape { }
An abstract method is a method w/o a
body
public abstract double area();
(Only) Abstract classes can have abstract
methods
In fact, any class with an abstract method
is automatically an abstract class 27
UMBC CMSC 331 Java
ExampleExample
abstract classabstract class
public abstract class Shape {
public abstract double area(); // Abstract methods: note
public abstract double circumference();// semicolon instead of body.
}
class Circle extends Shape {
public static final double PI = 3.14159265358979323846;
protected double r; // Instance data
public Circle(double r) { this.r = r; } // Constructor
public double getRadius() { return r; } // Accessor
public double area() { return PI*r*r; } // Implementations of
public double circumference() { return 2*PI*r; } // abstract methods.
}
class Rectangle extends Shape {
protected double w, h; // Instance data
public Rectangle(double w, double h) { // Constructor
this.w = w; this.h = h;
}
public double getWidth() { return w; } // Accessor method
public double getHeight() { return h; } // Another accessor
public double area() { return w*h; } // Implementations of
public double circumference() { return 2*(w + h); } // abstract methods. 28
UMBC CMSC 331 Java
Syntax NotesSyntax Notes
No global variables
◩ class variables and methods may be applied to
any instance of an object
◩ methods may have local (private?) variables
No pointers
◩ but complex data objects are “referenced”
Other parts of Java are borrowed from
PL/I, Modula, and other languages
29

Weitere Àhnliche Inhalte

Was ist angesagt?

Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...JAINAM KAPADIYA
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectOUM SAOKOSAL
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in javaMahmoud Ali
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS Shivam Singh
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptskishorethoutam
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziqSonu WIZIQ
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Conceptsmdfkhan625
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Majid Saeed
 
Unit ii
Unit   iiUnit   ii
Unit iidonny101
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 

Was ist angesagt? (20)

Core Java
Core JavaCore Java
Core Java
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...Method overloading, recursion, passing and returning objects from method, new...
Method overloading, recursion, passing and returning objects from method, new...
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
Core java
Core javaCore java
Core java
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
Kotlin
KotlinKotlin
Kotlin
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 

Ähnlich wie Java

Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Java assignment help
Java assignment helpJava assignment help
Java assignment helpJacob William
 
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)quantumiq448
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalorerajkamaltibacademy
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorialrajkamaltibacademy
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2Kamlesh Singh
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interfaceShubham Sharma
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.pptEmanAsem4
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPTkishu0005
 

Ähnlich wie Java (20)

Java basic
Java basicJava basic
Java basic
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java assignment help
Java assignment helpJava assignment help
Java assignment help
 
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
Java PRESENTATION(PACKAGES,CLASSES,VARIABLES,FLOW CONTROL,EXCEPTION)
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalore
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Inheritance
InheritanceInheritance
Inheritance
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Interface
InterfaceInterface
Interface
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 

Mehr von Khasim Cise

Scatter gather in mule
Scatter gather in muleScatter gather in mule
Scatter gather in muleKhasim Cise
 
Collections in Java
Collections in JavaCollections in Java
Collections in JavaKhasim Cise
 
Mule using Salesforce
Mule using SalesforceMule using Salesforce
Mule using SalesforceKhasim Cise
 
ESB introduction using Mule
ESB introduction using MuleESB introduction using Mule
ESB introduction using MuleKhasim Cise
 
Mule Fundamentals
Mule FundamentalsMule Fundamentals
Mule FundamentalsKhasim Cise
 
Introduction to mule esb
Introduction to mule esbIntroduction to mule esb
Introduction to mule esbKhasim Cise
 
Introduction to WebServices
Introduction to WebServicesIntroduction to WebServices
Introduction to WebServicesKhasim Cise
 
SunMicroSystems
SunMicroSystemsSunMicroSystems
SunMicroSystemsKhasim Cise
 
1. web services
1. web services1. web services
1. web servicesKhasim Cise
 
Introduction to mule esb
Introduction to mule esbIntroduction to mule esb
Introduction to mule esbKhasim Cise
 

Mehr von Khasim Cise (12)

Scatter gather in mule
Scatter gather in muleScatter gather in mule
Scatter gather in mule
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
Mule using Salesforce
Mule using SalesforceMule using Salesforce
Mule using Salesforce
 
Java
JavaJava
Java
 
ESB introduction using Mule
ESB introduction using MuleESB introduction using Mule
ESB introduction using Mule
 
Mule Fundamentals
Mule FundamentalsMule Fundamentals
Mule Fundamentals
 
Introduction to mule esb
Introduction to mule esbIntroduction to mule esb
Introduction to mule esb
 
Mule ESB
Mule ESBMule ESB
Mule ESB
 
Introduction to WebServices
Introduction to WebServicesIntroduction to WebServices
Introduction to WebServices
 
SunMicroSystems
SunMicroSystemsSunMicroSystems
SunMicroSystems
 
1. web services
1. web services1. web services
1. web services
 
Introduction to mule esb
Introduction to mule esbIntroduction to mule esb
Introduction to mule esb
 

KĂŒrzlich hochgeladen

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraĂșjo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 

KĂŒrzlich hochgeladen (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls đŸ„° 8617370543 Service Offer VIP Hot Model
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Java

  • 1. UMBC CMSC 331 Java JAVA BASICSJAVA BASICS Presented ByPresented By KhasimKhasim
  • 2. UMBC CMSC 331 Java Comments are almost like C++Comments are almost like C++ The javadoc program generates HTML API documentation from the “javadoc” style comments in your code. 2 /* This kind of comment can span multiple lines */ // This kind is to the end of the line /** * This kind of comment is a special * ‘javadoc’ style comment */
  • 3. UMBC CMSC 331 Java An example of a classAn example of a class 3 class Person { String name; int age; void birthday ( ) { age++; System.out.println (name + ' is now ' + age); } } Variable Method
  • 4. UMBC CMSC 331 Java ScopingScoping  As in C/C++, scope is determined by the placement of curly braces {}.  A variable defined within a scope is available only to the end of that scope. 4 { int x = 12; /* only x available */ { int q = 96; /* both x and q available */ } /* only x available */ /* q “out of scope” */ } { int x = 12; { int x = 96; /* illegal */ } } This is ok in C/C++ but not in Java.
  • 5. UMBC CMSC 331 Java An array is an objectAn array is an object  Person mary = new Person ( );  int myArray[ ] = new int[5];  int myArray[ ] = {1, 4, 9, 16, 25};  String languages [ ] = {"Prolog", "Java"};  Since arrays are objects they are allocated dynamically  Arrays, like all objects, are subject to garbage collection when no more references remain ◩ so fewer memory leaks ◩ Java doesn’t have pointers! 5
  • 6. UMBC CMSC 331 Java Scope of ObjectsScope of Objects Java objects don’t have the same lifetimes as primitives. When you create a Java object using new, it hangs around past the end of the scope. Here, the scope of name s is delimited by the {}s but the String object hangs around until GC’d { String s = new String("a string"); 6
  • 7. UMBC CMSC 331 Java Methods, arguments and return valuesMethods, arguments and return values Java methods are like C/C++ functions. General case: returnType methodName ( arg1, arg2, 
 argN) { methodBody } The return keyword exits a method optionally with a value int storage(String s) {return s.length() * 2;} boolean flag() { return true; } float naturalLogBase() { return 2.718f; } void nothing() { return; } void nothing2() {} 7
  • 8. UMBC CMSC 331 Java The static keywordThe static keyword Java methods and variables can be declared static These exist independent of any object This means that a Class’s ◩ static methods can be called even if no objects of that class have been created and ◩ static data is “shared” by all instances (i.e., one rvalue per class instead of one per instance 8 class StaticTest {static int i = 47;} StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); // st1.i == st2.I == 47 StaticTest.i++; // or st1.I++ or st2.I++ // st1.i == st2.I == 48
  • 9. UMBC CMSC 331 Java Array OperationsArray Operations Subscripts always start at 0 as in C Subscript checking is done automatically Certain operations are defined on arrays of objects, as for other classes ◩ e.g. myArray.length == 5 9
  • 10. UMBC CMSC 331 Java ExampleExample ProgramsPrograms
  • 11. Echo.javaEcho.java C:UMBC331java>type echo.java // This is the Echo example from the Sun tutorial class echo { public static void main(String args[]) { for (int i=0; i < args.length; i++) { System.out.println( args[i] ); } } } C:UMBC331java>javac echo.java C:UMBC331java>java echo this is pretty silly this is pretty silly C:UMBC331java>
  • 12. UMBC CMSC 331 Java Factorial ExampleFactorial Example /** * This program computes the factorial of a number */ public class Factorial { // Define a class public static void main(String[] args) { // The program starts here int input = Integer.parseInt(args[0]); // Get the user's input double result = factorial(input); // Compute the factorial System.out.println(result); // Print out the result } // The main() method ends here public static double factorial(int x) { // This method computes x! if (x < 0) // Check for bad input return 0.0; // if bad, return 0 double fact = 1.0; // Begin with an initial value while(x > 1) { // Loop until x equals 1 fact = fact * x; // multiply by x each time x = x - 1; // and then decrement x } // Jump back to the star of loop return fact; // Return the result 12 From Java in a Nutshell
  • 13. UMBC CMSC 331 Java JAVA ClassesJAVA Classes  The class is the fundamental concept in JAVA (and other OOPLs)  A class describes some data object(s), and the operations (or methods) that can be applied to those objects  Every object and method in Java belongs to a class  Classes have data (fields) and code (methods) and classes (member classes or inner classes)  Static methods and fields belong to the class itself  Others belong to instances 13
  • 14. UMBC CMSC 331 Java ExampleExample public class Circle { // A class field public static final double PI= 3.14159; // A useful constant // A class method: just compute a value based on the arguments public static double radiansToDegrees(double rads) { return rads * 180 / PI; } // An instance field public double r; // The radius of the circle // Two methods which operate on the instance fields of an object public double area() { // Compute the area of the circle return PI * r * r; } public double circumference() { // Compute the circumference of the circle return 2 * PI * r; } } 14
  • 15. UMBC CMSC 331 Java ConstructorsConstructors Classes should define one or more methods to create or construct instances of the class Their name is the same as the class name ◩ note deviation from convention that methods begin with lower case Constructors are differentiated by the number and types of their arguments ◩ An example of overloading If you don’t define a constructor, a default one will be created. Constructors automatically invoke the zero argument constructor of their superclass when they begin (note that this yields a recursive process!) 15
  • 16. UMBC CMSC 331 Java Constructor exampleConstructor example public class Circle { public static final double PI = 3.14159; // A constant public double r; // instance field holds circle’s radius // The constructor method: initialize the radius field public Circle(double r) { this.r = r; } // Constructor to use if no arguments public Circle() { r = 1.0; } // better: public Circle() { this(1.0); } // The instance methods: compute values based on radius public double circumference() { return 2 * PI * r; } public double area() { return PI * r*r; } } 16 this.r refers to the r field of the class This() refers to a constructor for the class
  • 17. UMBC CMSC 331 Java Extending a classExtending a class  Class hierarchies reflect subclass-superclass relations among classes.  One arranges classes in hierarchies: ◩ A class inherits instance variables and instance methods from all of its superclasses. Tree -> BinaryTree -> BST ◩ You can specify only ONE superclass for any class.  When a subclass-superclass chain contains multiple instance methods with the same signature (name, arity, and argument types), the one closest to the target instance in the subclass- superclass chain is the one executed. ◩ All others are shadowed/overridden.  Something like multiple inheritance can be done via interfaces (more on this later)  What’s the superclass of a class defined without an extends clause? 17
  • 18. UMBC CMSC 331 Java Extending a classExtending a class public class PlaneCircle extends Circle { // We automatically inherit the fields and methods of Circle, // so we only have to put the new stuff here. // New instance fields that store the center point of the circle public double cx, cy; // A new constructor method to initialize the new fields // It uses a special syntax to invoke the Circle() constructor public PlaneCircle(double r, double x, double y) { super(r); // Invoke the constructor of the superclass, Circle() this.cx = x; // Initialize the instance field cx this.cy = y; // Initialize the instance field cy } // The area() and circumference() methods are inherited from Circle // A new instance method that checks whether a point is inside the circle // Note that it uses the inherited instance field r public boolean isInside(double x, double y) { double dx = x - cx, dy = y - cy; // Distance from center double distance = Math.sqrt(dx*dx + dy*dy); // Pythagorean theorem return (distance < r); // Returns true or false 18
  • 19. UMBC CMSC 331 Java Overloading, overwriting, and shadowingOverloading, overwriting, and shadowing  Overloading occurs when Java can distinguish two procedures with the same name by examining the number or types of their parameters.  Shadowing or overriding occurs when two procedures with the same signature (name, the same number of parameters, and the same parameter types) are defined in different classes, one of which is a superclass of the other. 19
  • 20. UMBC CMSC 331 Java On designing class hierarchiesOn designing class hierarchies  Programs should obey the explicit-representation principle, with classes included to reflect natural categories.  Programs should obey the no-duplication principle, with instance methods situated among class definitions to facilitate sharing.  Programs should obey the look-it-up principle, with class definitions including instance variables for stable, frequently requested information.  Programs should obey the need-to-know principle, with public interfaces designed to restrict instance-variable and instance-method access, thus facilitating the improvement and maintenance of nonpublic program elements.  If you find yourself using the phrase an X is aY when describing the relation between two classes, then the X class is a subclass of theY class.  If you find yourself using X has aY when describing the relation between two classes, then instances of theY class appear as parts of instances of the X class. 20
  • 21. UMBC CMSC 331 Java Data hiding and encapsulationData hiding and encapsulation Data-hiding or encapsulation is an important part of the OO paradigm. Classes should carefully control access to their data and methods in order to ◩ Hide the irrelevant implementation-level details so they can be easily changed ◩ Protect the class against accidental or malicious damage. ◩ Keep the externally visible class simple and easy to document Java has a simple access control mechanism to help with encapsulation 21
  • 22. UMBC CMSC 331 Java ExampleExample encapsulationencapsulation package shapes; // Specify a package for the class public class Circle { // The class is still public public static final double PI = 3.14159; protected double r; // Radius is hidden, but visible to subclasses // A method to enforce the restriction on the radius // This is an implementation detail that may be of interest to subclasses protected checkRadius(double radius) { if (radius < 0.0) throw new IllegalArgumentException("radius may not be negative."); } // The constructor method public Circle(double r) {checkRadius(r); this.r = r; } // Public data accessor methods public double getRadius() { return r; }; public void setRadius(double r) { checkRadius(r); this.r = r;} // Methods to operate on the instance field public double area() { return PI * r * r; } public double circumference() { return 2 * PI * r; } } 22
  • 23. UMBC CMSC 331 Java Access controlAccess control Access to packages ◩ Java offers no control mechanisms for packages. ◩ If you can find and read the package you can access it Access to classes ◩ All top level classes in package P are accessible anywhere in P ◩ All public top-level classes in P are accessible anywhere Access to class members (in class C in package P) ◩ Public: accessible anywhere C is accessible 23
  • 24. 24
  • 25. UMBC CMSC 331 Java Getters and settersGetters and setters  A getter is a method that extracts information from an instance. ◩ One benefit: you can include additional computation in a getter.  A setter is a method that inserts information into an instance (also known as mutators). ◩ A setter method can check the validity of the new value (e.g., between 1 and 7) or trigger a side effect (e.g., update a display)  Getters and setters can be used even without underlying matching variables  Considered good OO practice  Essential to javabeans  Convention: for variable fooBar of type fbtype, define ◩ getFooBar() ◩ setFooBar(fbtype x) 25
  • 26. UMBC CMSC 331 Java ExampleExample getters and settersgetters and setters package shapes; // Specify a package for the class public class Circle { // The class is still public // This is a generally useful constant, so we keep it public public static final double PI = 3.14159; protected double r; // Radius is hidden, but visible to subclasses // A method to enforce the restriction on the radius // This is an implementation detail that may be of interest to subclasses protected checkRadius(double radius) { if (radius < 0.0) throw new IllegalArgumentException("radius may not be negative."); } // The constructor method public Circle(double r) { checkRadius(r); this.r = r;} // Public data accessor methods public double getRadius() { return r; }; public void setRadius(double r) { checkRadius(r); this.r = r;} // Methods to operate on the instance field public double area() { return PI * r * r; } public double circumference() { return 2 * PI * r; } 26
  • 27. UMBC CMSC 331 Java Abstract classes and methodsAbstract classes and methods Abstract vs. concrete classes Abstract classes can not be instantiated public abstract class shape { } An abstract method is a method w/o a body public abstract double area(); (Only) Abstract classes can have abstract methods In fact, any class with an abstract method is automatically an abstract class 27
  • 28. UMBC CMSC 331 Java ExampleExample abstract classabstract class public abstract class Shape { public abstract double area(); // Abstract methods: note public abstract double circumference();// semicolon instead of body. } class Circle extends Shape { public static final double PI = 3.14159265358979323846; protected double r; // Instance data public Circle(double r) { this.r = r; } // Constructor public double getRadius() { return r; } // Accessor public double area() { return PI*r*r; } // Implementations of public double circumference() { return 2*PI*r; } // abstract methods. } class Rectangle extends Shape { protected double w, h; // Instance data public Rectangle(double w, double h) { // Constructor this.w = w; this.h = h; } public double getWidth() { return w; } // Accessor method public double getHeight() { return h; } // Another accessor public double area() { return w*h; } // Implementations of public double circumference() { return 2*(w + h); } // abstract methods. 28
  • 29. UMBC CMSC 331 Java Syntax NotesSyntax Notes No global variables ◩ class variables and methods may be applied to any instance of an object ◩ methods may have local (private?) variables No pointers ◩ but complex data objects are “referenced” Other parts of Java are borrowed from PL/I, Modula, and other languages 29