Java Basics

F
UMBC CMSC 331 Java
JAVA BASICSJAVA BASICS
Presented ByPresented By
KHANKHAN
UMBC CMSC 331 Java 2
Comments are almost like C++
The javadoc program generates HTML API documentation
from the “javadoc” style comments in your code.
/* 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 3
An example of a class
class Person {
String name;
int age;
void birthday ( ) {
age++;
System.out.println (name +
' is now ' + age);
}
}
Variable
Method
UMBC CMSC 331 Java 4
Scoping
• 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.
{ 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 5
An 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!
UMBC CMSC 331 Java 6
Scope 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");
} /* end of scope */
UMBC CMSC 331 Java 7
Methods, 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() {}
UMBC CMSC 331 Java 8
The 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
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 9
Array 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
UMBC CMSC 331 Java
ExampleExample
ProgramsPrograms
Echo.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 12
Factorial 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
} // factorial() ends here
} // The class ends here
From Java in a Nutshell
UMBC CMSC 331 Java 13
JAVA 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
UMBC CMSC 331 Java 14
Example
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;
}
}
UMBC CMSC 331 Java 15
Constructors
• 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!)
UMBC CMSC 331 Java 16
Constructor 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; }
}
this.r refers to the r
field of the class
This() refers to a
constructor for the class
UMBC CMSC 331 Java 17
Extending 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?
UMBC CMSC 331 Java 18
Extending 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
}
}
UMBC CMSC 331 Java 19
Overloading, 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.
UMBC CMSC 331 Java 20
On 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 a Y when describing the
relation between two classes, then the X class is a subclass of the Y class.
• If you find yourself using X has a Y when describing the relation between
two classes, then instances of the Y class appear as parts of instances of the
X class.
UMBC CMSC 331 Java 21
Data 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
– Modifiers: public, protected, private, and package
(default)
UMBC CMSC 331 Java 22
Example
encapsulation
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; }
}
UMBC CMSC 331 Java 23
Access 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
– Protected: accessible in P and to any of C’s subclasses
– Private: only accessible within class C
– Package: only accessible in P (the default)
UMBC CMSC 331 Java 24
UMBC CMSC 331 Java 25
Getters 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)
UMBC CMSC 331 Java 26
Example
getters 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; }
}
UMBC CMSC 331 Java 27
Abstract 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
UMBC CMSC 331 Java 28
Example
abstract 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.
}
UMBC CMSC 331 Java 29
Syntax 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
1 von 29

Recomendados

Java basic tutorial von
Java basic tutorialJava basic tutorial
Java basic tutorialBui Kiet
573 views29 Folien
Java Basics von
Java BasicsJava Basics
Java BasicsRajkattamuri
637 views29 Folien
Java von
JavaJava
Javajaveed_mhd
277 views29 Folien
Java von
JavaJava
JavaKhasim Cise
456 views29 Folien
Java02 von
Java02Java02
Java02Vinod siragaon
1.8K views29 Folien
Java unit2 von
Java unit2Java unit2
Java unit2Abhishek Khune
1.2K views47 Folien

Más contenido relacionado

Was ist angesagt?

Classes, objects in JAVA von
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
28.4K views27 Folien
JAVA Notes - All major concepts covered with examples von
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
2.7K views10 Folien
02 java basics von
02 java basics02 java basics
02 java basicsbsnl007
104 views25 Folien
Core java concepts von
Core java concepts Core java concepts
Core java concepts javeed_mhd
491 views15 Folien
Java OOP Programming language (Part 3) - Class and Object von
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
482 views22 Folien
Class introduction in java von
Class introduction in javaClass introduction in java
Class introduction in javayugandhar vadlamudi
531 views14 Folien

Was ist angesagt?(20)

Classes, objects in JAVA von Abhilash Nair
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair28.4K views
02 java basics von bsnl007
02 java basics02 java basics
02 java basics
bsnl007104 views
Core java concepts von javeed_mhd
Core java concepts Core java concepts
Core java concepts
javeed_mhd491 views
Java OOP Programming language (Part 3) - Class and Object von OUM SAOKOSAL
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
OUM SAOKOSAL482 views
Introduction to class in java von kamal kotecha
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha16.3K views
Ppt on this and super keyword von tanu_jaswal
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal10.6K views
Overloading and overriding in vb.net von suraj pandey
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
suraj pandey7.1K views
Java OOP Programming language (Part 5) - Inheritance von OUM SAOKOSAL
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL611 views
Pi j3.2 polymorphism von mcollison
Pi j3.2 polymorphismPi j3.2 polymorphism
Pi j3.2 polymorphism
mcollison208 views
Core java complete ppt(note) von arvind pandey
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey5.8K views
Method overloading, recursion, passing and returning objects from method, new... von JAINAM KAPADIYA
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 KAPADIYA1.1K views
Core java concepts von Ram132
Core java  conceptsCore java  concepts
Core java concepts
Ram13235.8K views
Object and Classes in Java von backdoor
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor3.1K views

Destacado

mule salesforce von
mule salesforcemule salesforce
mule salesforceF K
637 views19 Folien
Mule with stored procedure von
Mule with stored procedureMule with stored procedure
Mule with stored procedureF K
387 views14 Folien
Scatter gatherinmule von
Scatter gatherinmuleScatter gatherinmule
Scatter gatherinmuleF K
441 views10 Folien
Simple webservice with vm von
Simple webservice with vmSimple webservice with vm
Simple webservice with vmF K
224 views11 Folien
Mule esb Data Weave von
Mule esb Data WeaveMule esb Data Weave
Mule esb Data WeaveF K
384 views7 Folien
Esb Basics von
Esb BasicsEsb Basics
Esb BasicsF K
408 views33 Folien

Destacado(18)

mule salesforce von F K
mule salesforcemule salesforce
mule salesforce
F K637 views
Mule with stored procedure von F K
Mule with stored procedureMule with stored procedure
Mule with stored procedure
F K387 views
Scatter gatherinmule von F K
Scatter gatherinmuleScatter gatherinmule
Scatter gatherinmule
F K441 views
Simple webservice with vm von F K
Simple webservice with vmSimple webservice with vm
Simple webservice with vm
F K224 views
Mule esb Data Weave von F K
Mule esb Data WeaveMule esb Data Weave
Mule esb Data Weave
F K384 views
Esb Basics von F K
Esb BasicsEsb Basics
Esb Basics
F K408 views
Selenium using Java von F K
Selenium using JavaSelenium using Java
Selenium using Java
F K720 views
Idempotent filter in Mule von F K
Idempotent filter in MuleIdempotent filter in Mule
Idempotent filter in Mule
F K362 views
Trenton Dierkes - Sound Financial Management von Trenton Dierkes
Trenton Dierkes - Sound Financial ManagementTrenton Dierkes - Sound Financial Management
Trenton Dierkes - Sound Financial Management
Trenton Dierkes224 views
Creating dynamic json in Mule von F K
Creating dynamic json in MuleCreating dynamic json in Mule
Creating dynamic json in Mule
F K417 views
Caching and invalidating with managed store von F K
Caching and invalidating with managed storeCaching and invalidating with managed store
Caching and invalidating with managed store
F K246 views
Automatic documentation with mule von F K
Automatic documentation with muleAutomatic documentation with mule
Automatic documentation with mule
F K386 views
ESB Presentation von F K
ESB PresentationESB Presentation
ESB Presentation
F K1.4K views
Introduction to mule esb's von F K
Introduction to mule esb's Introduction to mule esb's
Introduction to mule esb's
F K567 views
File component von F K
File component File component
File component
F K146 views
Message properties component von F K
Message properties componentMessage properties component
Message properties component
F K128 views
Commit a project in svn using svn plugin in anypoint studio von F K
Commit a project in svn using svn plugin in anypoint studioCommit a project in svn using svn plugin in anypoint studio
Commit a project in svn using svn plugin in anypoint studio
F K575 views
Choice component von F K
Choice component Choice component
Choice component
F K104 views

Similar a Java Basics

Core java von
Core javaCore java
Core javaRajkattamuri
196 views15 Folien
Java Concepts von
Java ConceptsJava Concepts
Java ConceptsAbdulImrankhan7
347 views15 Folien
Core Java von
Core JavaCore Java
Core JavaKhasim Saheb
725 views15 Folien
Best Core Java Training In Bangalore von
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalorerajkamaltibacademy
31 views15 Folien
Core java concepts von
Core    java  conceptsCore    java  concepts
Core java conceptskishorethoutam
2.7K views15 Folien
Corejava Training in Bangalore Tutorial von
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorialrajkamaltibacademy
108 views24 Folien

Similar a Java Basics(20)

Core Java Concepts von mdfkhan625
Core Java ConceptsCore Java Concepts
Core Java Concepts
mdfkhan625349 views
02-OOP with Java.ppt von EmanAsem4
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
EmanAsem44 views
Java oops PPT von kishu0005
Java oops PPTJava oops PPT
Java oops PPT
kishu0005669 views
Unit 1 Part - 3 constructor Overloading Static.ppt von DeepVala5
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala56 views
3java Advanced Oop von Adil Jafri
3java Advanced Oop3java Advanced Oop
3java Advanced Oop
Adil Jafri233 views
java: basics, user input, data type, constructor von Shivam Singhal
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
Shivam Singhal4.8K views
Csharp4 objects and_types von Abed Bukhari
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari582 views

Más de F K

WebServices introduction in Mule von
WebServices introduction in MuleWebServices introduction in Mule
WebServices introduction in MuleF K
527 views38 Folien
Testing soapui von
Testing soapuiTesting soapui
Testing soapuiF K
208 views14 Folien
Java For Begineers von
Java For BegineersJava For Begineers
Java For BegineersF K
171 views13 Folien
Vm component von
Vm componentVm component
Vm componentF K
171 views9 Folien
Until successful component in mule von
Until successful component in muleUntil successful component in mule
Until successful component in muleF K
336 views8 Folien
Quartz component von
Quartz componentQuartz component
Quartz componentF K
178 views9 Folien

Más de F K(19)

WebServices introduction in Mule von F K
WebServices introduction in MuleWebServices introduction in Mule
WebServices introduction in Mule
F K527 views
Testing soapui von F K
Testing soapuiTesting soapui
Testing soapui
F K208 views
Java For Begineers von F K
Java For BegineersJava For Begineers
Java For Begineers
F K171 views
Vm component von F K
Vm componentVm component
Vm component
F K171 views
Until successful component in mule von F K
Until successful component in muleUntil successful component in mule
Until successful component in mule
F K336 views
Quartz component von F K
Quartz componentQuartz component
Quartz component
F K178 views
Mule management console installation von F K
Mule management console installation Mule management console installation
Mule management console installation
F K384 views
Mule esb made system integration easy von F K
Mule esb made system integration easy Mule esb made system integration easy
Mule esb made system integration easy
F K303 views
Junit in mule von F K
Junit in muleJunit in mule
Junit in mule
F K433 views
Install sonarqube plugin in anypoint von F K
Install sonarqube plugin in anypoint Install sonarqube plugin in anypoint
Install sonarqube plugin in anypoint
F K352 views
Github plugin setup in anypoint studio von F K
Github plugin setup in anypoint studio Github plugin setup in anypoint studio
Github plugin setup in anypoint studio
F K446 views
For each component von F K
For each component For each component
For each component
F K180 views
Filter expression von F K
Filter expression Filter expression
Filter expression
F K196 views
Database component von F K
Database component Database component
Database component
F K147 views
Mule with drools von F K
Mule with droolsMule with drools
Mule with drools
F K354 views
Converting with custom transformer von F K
Converting with custom transformerConverting with custom transformer
Converting with custom transformer
F K190 views
Cache for community edition von F K
Cache for community editionCache for community edition
Cache for community edition
F K196 views
Multithreading von F K
MultithreadingMultithreading
Multithreading
F K461 views
Mule von F K
MuleMule
Mule
F K402 views

Último

Five Things You SHOULD Know About Postman von
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About PostmanPostman
25 views43 Folien
PharoJS - Zürich Smalltalk Group Meetup November 2023 von
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023Noury Bouraqadi
113 views17 Folien
Throughput von
ThroughputThroughput
ThroughputMoisés Armani Ramírez
32 views11 Folien
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor... von
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...Vadym Kazulkin
70 views64 Folien
GigaIO: The March of Composability Onward to Memory with CXL von
GigaIO: The March of Composability Onward to Memory with CXLGigaIO: The March of Composability Onward to Memory with CXL
GigaIO: The March of Composability Onward to Memory with CXLCXL Forum
126 views12 Folien
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum... von
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...NUS-ISS
28 views35 Folien

Último(20)

Five Things You SHOULD Know About Postman von Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman25 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 von Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi113 views
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor... von Vadym Kazulkin
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
Vadym Kazulkin70 views
GigaIO: The March of Composability Onward to Memory with CXL von CXL Forum
GigaIO: The March of Composability Onward to Memory with CXLGigaIO: The March of Composability Onward to Memory with CXL
GigaIO: The March of Composability Onward to Memory with CXL
CXL Forum126 views
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum... von NUS-ISS
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
NUS-ISS28 views
Understanding GenAI/LLM and What is Google Offering - Felix Goh von NUS-ISS
Understanding GenAI/LLM and What is Google Offering - Felix GohUnderstanding GenAI/LLM and What is Google Offering - Felix Goh
Understanding GenAI/LLM and What is Google Offering - Felix Goh
NUS-ISS39 views
Web Dev - 1 PPT.pdf von gdsczhcet
Web Dev - 1 PPT.pdfWeb Dev - 1 PPT.pdf
Web Dev - 1 PPT.pdf
gdsczhcet52 views
Samsung: CMM-H Tiered Memory Solution with Built-in DRAM von CXL Forum
Samsung: CMM-H Tiered Memory Solution with Built-in DRAMSamsung: CMM-H Tiered Memory Solution with Built-in DRAM
Samsung: CMM-H Tiered Memory Solution with Built-in DRAM
CXL Forum105 views
Transcript: The Details of Description Techniques tips and tangents on altern... von BookNet Canada
Transcript: The Details of Description Techniques tips and tangents on altern...Transcript: The Details of Description Techniques tips and tangents on altern...
Transcript: The Details of Description Techniques tips and tangents on altern...
BookNet Canada119 views
The details of description: Techniques, tips, and tangents on alternative tex... von BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada110 views
Webinar : Competing for tomorrow’s leaders – How MENA insurers can win the wa... von The Digital Insurer
Webinar : Competing for tomorrow’s leaders – How MENA insurers can win the wa...Webinar : Competing for tomorrow’s leaders – How MENA insurers can win the wa...
Webinar : Competing for tomorrow’s leaders – How MENA insurers can win the wa...
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi von Fwdays
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi
"AI Startup Growth from Idea to 1M ARR", Oleksandr Uspenskyi
Fwdays26 views
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen... von NUS-ISS
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...
Upskilling the Evolving Workforce with Digital Fluency for Tomorrow's Challen...
NUS-ISS23 views
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV von Splunk
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
.conf Go 2023 - How KPN drives Customer Satisfaction on IPTV
Splunk86 views
"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy von Fwdays
"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy
"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy
Fwdays40 views
Liqid: Composable CXL Preview von CXL Forum
Liqid: Composable CXL PreviewLiqid: Composable CXL Preview
Liqid: Composable CXL Preview
CXL Forum121 views
MemVerge: Gismo (Global IO-free Shared Memory Objects) von CXL Forum
MemVerge: Gismo (Global IO-free Shared Memory Objects)MemVerge: Gismo (Global IO-free Shared Memory Objects)
MemVerge: Gismo (Global IO-free Shared Memory Objects)
CXL Forum112 views

Java Basics

  • 1. UMBC CMSC 331 Java JAVA BASICSJAVA BASICS Presented ByPresented By KHANKHAN
  • 2. UMBC CMSC 331 Java 2 Comments are almost like C++ The javadoc program generates HTML API documentation from the “javadoc” style comments in your code. /* 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 3 An example of a class class Person { String name; int age; void birthday ( ) { age++; System.out.println (name + ' is now ' + age); } } Variable Method
  • 4. UMBC CMSC 331 Java 4 Scoping • 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. { 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 5 An 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!
  • 6. UMBC CMSC 331 Java 6 Scope 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"); } /* end of scope */
  • 7. UMBC CMSC 331 Java 7 Methods, 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() {}
  • 8. UMBC CMSC 331 Java 8 The 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 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 9 Array 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
  • 10. UMBC CMSC 331 Java ExampleExample ProgramsPrograms
  • 11. Echo.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 12 Factorial 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 } // factorial() ends here } // The class ends here From Java in a Nutshell
  • 13. UMBC CMSC 331 Java 13 JAVA 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
  • 14. UMBC CMSC 331 Java 14 Example 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; } }
  • 15. UMBC CMSC 331 Java 15 Constructors • 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!)
  • 16. UMBC CMSC 331 Java 16 Constructor 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; } } this.r refers to the r field of the class This() refers to a constructor for the class
  • 17. UMBC CMSC 331 Java 17 Extending 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?
  • 18. UMBC CMSC 331 Java 18 Extending 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 } }
  • 19. UMBC CMSC 331 Java 19 Overloading, 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.
  • 20. UMBC CMSC 331 Java 20 On 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 a Y when describing the relation between two classes, then the X class is a subclass of the Y class. • If you find yourself using X has a Y when describing the relation between two classes, then instances of the Y class appear as parts of instances of the X class.
  • 21. UMBC CMSC 331 Java 21 Data 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 – Modifiers: public, protected, private, and package (default)
  • 22. UMBC CMSC 331 Java 22 Example encapsulation 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; } }
  • 23. UMBC CMSC 331 Java 23 Access 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 – Protected: accessible in P and to any of C’s subclasses – Private: only accessible within class C – Package: only accessible in P (the default)
  • 24. UMBC CMSC 331 Java 24
  • 25. UMBC CMSC 331 Java 25 Getters 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)
  • 26. UMBC CMSC 331 Java 26 Example getters 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; } }
  • 27. UMBC CMSC 331 Java 27 Abstract 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
  • 28. UMBC CMSC 331 Java 28 Example abstract 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. }
  • 29. UMBC CMSC 331 Java 29 Syntax 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