SlideShare a Scribd company logo
1 of 15
CORECORE JAVAJAVA
CONCEPTSCONCEPTS
Comments are almost like C++Comments are almost like C++
• The javadoc program generates HTML APIThe javadoc program generates HTML API
documentation from the “javadoc” style comments indocumentation from the “javadoc” style comments in
your code.your code.
/* This kind comment can span multiple lines */
// This kind is of to the end of the line
//* This kind of comment is a special
* ‘javadoc’ style comment
*/
JAVA ClassesJAVA Classes
• TheThe classclass is the fundamental concept in JAVA (and otheris the fundamental concept in JAVA (and other
OOPLs)OOPLs)
• A class describes some data object(s), and theA class describes some data object(s), and the
operations (or methods) that can be applied to thoseoperations (or methods) that can be applied to those
objectsobjects
• Every object and method in Java belongs to a classEvery object and method in Java belongs to a class
• Classes have data (fields) and code (methods) andClasses have data (fields) and code (methods) and
classes (member classes or inner classes)classes (member classes or inner classes)
• Static methods and fields belong to the class itselfStatic methods and fields belong to the class itself
• Others belong to instancesOthers belong to instances
An example of a classAn example of a class
class Person { Variable
String name;
int age; Method
void birthday ( )
{
age++;
System.out.println (name +
' is now ' + age);
}
}
ScopingScoping
As in C/C++, scope is determined by the placement of curly braces {}.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.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.
Scope of ObjectsScope of Objects
• Java objects don’t have the same lifetimes asJava objects don’t have the same lifetimes as
primitives.primitives.
• When you create a Java object usingWhen you create a Java object using newnew, it, it
hangs around past the end of the scope.hangs around past the end of the scope.
• Here, the scope of name s is delimited by the {}sHere, the scope of name s is delimited by the {}s
but the String object hangs around until GC’dbut the String object hangs around until GC’d
{{
String s = newString s = new String("aString("a string");string");
} /* end of scope */} /* end of scope */
TheThe staticstatic keywordkeyword
• Java methods and variables can be declared staticJava methods and variables can be declared static
• These existThese exist independent of any objectindependent of any object
• This means that a Class’sThis means that a Class’s
– static methods can be calledstatic methods can be called even if no objects of thateven if no objects of that
class have been created andclass have been created and
– static data is “shared” by all instances (i.e., one rvaluestatic data is “shared” by all instances (i.e., one rvalue
per class instead of one per instanceper 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
ExampleExample
public class Circle {public class Circle {
// A class field// A class field
public static final double PI= 3.14159; // A usefulpublic static final double PI= 3.14159; // A useful
constantconstant
// A class method: just compute a value based on the// A class method: just compute a value based on the
argumentsarguments
public static double radiansToDegrees(double rads) {public static double radiansToDegrees(double rads) {
return rads * 180 / PI;return rads * 180 / PI;
}}
// An instance field// An instance field
public double r; // The radius of thepublic double r; // The radius of the
circlecircle
// Two methods which operate on the instance fields of// Two methods which operate on the instance fields of
an objectan object
public double area() { // Compute the area ofpublic double area() { // Compute the area of
the circlethe circle
return PI * r * r;return PI * r * r;
}}
public double circumference() { // Compute thepublic double circumference() { // Compute the
circumference of the circlecircumference of the circle
return 2 * PI * r;return 2 * PI * r;
}}
}}
Array OperationsArray Operations
• Subscripts always start at 0 as in CSubscripts always start at 0 as in C
• Subscript checking is done automaticallySubscript checking is done automatically
• Certain operations are defined on arraysCertain operations are defined on arrays
of objects, as for other classesof objects, as for other classes
– e.g. myArray.length == 5e.g. myArray.length == 5
An array is an objectAn array is an object
• Person mary = new Person ( );Person mary = new Person ( );
• int myArray[ ] = new int[5];int myArray[ ] = new int[5];
• int myArray[ ] = {1, 4, 9, 16, 25};int myArray[ ] = {1, 4, 9, 16, 25};
• String languages [ ] = {"Prolog", "Java"};String languages [ ] = {"Prolog", "Java"};
• Since arrays are objects they are allocated dynamicallySince arrays are objects they are allocated dynamically
• Arrays, like all objects, are subject to garbage collectionArrays, like all objects, are subject to garbage collection
when no more references remainwhen no more references remain
– so fewer memory leaksso fewer memory leaks
– Java doesn’t have pointers!Java doesn’t have pointers!
ExampleExample
ProgramsPrograms
NSIT ,JetalpurNSIT ,Jetalpur
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
NSIT ,JetalpurNSIT ,Jetalpur
Factorial ExampleFactorial Example
/* This program computes the factorial of a number/* This program computes the factorial of a number
*/*/
public class Factorial { // Define a classpublic class Factorial { // Define a class
public static void main(String[] args) { // The program startspublic static void main(String[] args) { // The program starts
herehere
int input = Integer.parseInt(args[0]); // Get the user'sint input = Integer.parseInt(args[0]); // Get the user's
inputinput
double result = factorial(input); // Compute thedouble result = factorial(input); // Compute the
factorialfactorial
System.out.println(result); // Print out theSystem.out.println(result); // Print out the
resultresult
} // The main() method} // The main() method
ends hereends here
public static double factorial(int x) { // This methodpublic static double factorial(int x) { // This method
computes x!computes x!
if (x < 0) // Check for bad inputif (x < 0) // Check for bad input
return 0.0; // if bad, return 0return 0.0; // if bad, return 0
double fact = 1.0; // Begin with andouble fact = 1.0; // Begin with an
initial valueinitial value
while(x > 1) { // Loop until x equalswhile(x > 1) { // Loop until x equals
fact = fact * x; // multiply by xfact = fact * x; // multiply by x
each timeeach time
x = x - 1; // and thenx = x - 1; // and then
decrement xdecrement x
NSIT ,JetalpurNSIT ,Jetalpur
ConstructorsConstructors
• Classes should define one or more methods to createClasses should define one or more methods to create
or construct instances of the classor construct instances of the class
• Their name is the same as the class nameTheir name is the same as the class name
– note deviation from convention that methods begin withnote deviation from convention that methods begin with
lower caselower case
• Constructors are differentiated by the number andConstructors are differentiated by the number and
types of their argumentstypes of their arguments
– An example of overloadingAn example of overloading
• If you don’t define a constructor, a default one will beIf you don’t define a constructor, a default one will be
created.created.
• Constructors automatically invoke the zero argumentConstructors automatically invoke the zero argument
constructor of their superclass when they begin (noteconstructor of their superclass when they begin (note
that this yields a recursive process!)that this yields a recursive process!)
Methods, arguments andMethods, arguments and
return valuesreturn values
• Java methods are like C/C++ functions.Java methods are like C/C++ functions.
General case:General case:
returnTypereturnType methodNamemethodName (( arg1arg1,, arg2arg2, …, … argNargN))
{{
methodBodymethodBody
}}
The return keyword exits a method optionally with a valueThe return keyword exits a method optionally with a value
int storage(String s) {return s.length() * 2;}int storage(String s) {return s.length() * 2;}
boolean flag() { return true; }boolean flag() { return true; }
float naturalLogBase() { return 2.718f; }float naturalLogBase() { return 2.718f; }
void nothing() { return; }void nothing() { return; }
void nothing2() {}void nothing2() {}

More Related Content

What's hot

Java tutorials
Java tutorialsJava tutorials
Java tutorials
saryu2011
 

What's hot (18)

Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
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
 
Java Concepts
Java ConceptsJava Concepts
Java Concepts
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
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
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
05 Java Language And OOP Part V
05 Java Language And OOP Part V05 Java Language And OOP Part V
05 Java Language And OOP Part V
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
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
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Core Java
Core JavaCore Java
Core Java
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalore
 

Similar to Core Java Concepts

Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
Sandesh Sharma
 

Similar to Core Java Concepts (20)

Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java basic tutorial
Java basic tutorialJava basic tutorial
Java basic tutorial
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Java Basics
Java BasicsJava Basics
Java Basics
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Java
JavaJava
Java
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
 
Java
Java Java
Java
 
Java
JavaJava
Java
 
Module 1.pptx
Module 1.pptxModule 1.pptx
Module 1.pptx
 
Java
JavaJava
Java
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
Java
JavaJava
Java
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Ifi7184 lesson3
Ifi7184 lesson3Ifi7184 lesson3
Ifi7184 lesson3
 
Generic Programming
Generic ProgrammingGeneric Programming
Generic Programming
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 

More from mdfkhan625

More from mdfkhan625 (20)

Mapping and listing with mule
Mapping and listing with muleMapping and listing with mule
Mapping and listing with mule
 
How to use message properties component
How to use message properties componentHow to use message properties component
How to use message properties component
 
How to use expression filter
How to use expression filterHow to use expression filter
How to use expression filter
 
Data weave
Data weave Data weave
Data weave
 
Anypoint data gateway
Anypoint data gatewayAnypoint data gateway
Anypoint data gateway
 
Webservice with vm in mule
Webservice with vm in mule Webservice with vm in mule
Webservice with vm in mule
 
Validating soap request in mule
Validating soap request in mule Validating soap request in mule
Validating soap request in mule
 
Using xslt in mule
Using xslt in mule Using xslt in mule
Using xslt in mule
 
Groovy example in mule
Groovy example in mule Groovy example in mule
Groovy example in mule
 
Scatter gather flow control
Scatter gather flow control Scatter gather flow control
Scatter gather flow control
 
Mule with velocity
Mule with velocity Mule with velocity
Mule with velocity
 
Mule with rabbit mq
Mule with rabbit mq Mule with rabbit mq
Mule with rabbit mq
 
Mule with quartz
Mule with quartzMule with quartz
Mule with quartz
 
Mule with drools
Mule with drools Mule with drools
Mule with drools
 
Mule esb
Mule esb Mule esb
Mule esb
 
Idempotent filter with simple file
Idempotent filter with simple fileIdempotent filter with simple file
Idempotent filter with simple file
 
Creating dynamic json
Creating dynamic json Creating dynamic json
Creating dynamic json
 
Converting with custom transformer
Converting with custom transformer Converting with custom transformer
Converting with custom transformer
 
Caching and invalidating with managed store
Caching and invalidating with managed storeCaching and invalidating with managed store
Caching and invalidating with managed store
 
Cache for community edition
Cache for community edition Cache for community edition
Cache for community edition
 

Recently uploaded

TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

Core Java Concepts

  • 2. Comments are almost like C++Comments are almost like C++ • The javadoc program generates HTML APIThe javadoc program generates HTML API documentation from the “javadoc” style comments indocumentation from the “javadoc” style comments in your code.your code. /* This kind comment can span multiple lines */ // This kind is of to the end of the line //* This kind of comment is a special * ‘javadoc’ style comment */
  • 3. JAVA ClassesJAVA Classes • TheThe classclass is the fundamental concept in JAVA (and otheris the fundamental concept in JAVA (and other OOPLs)OOPLs) • A class describes some data object(s), and theA class describes some data object(s), and the operations (or methods) that can be applied to thoseoperations (or methods) that can be applied to those objectsobjects • Every object and method in Java belongs to a classEvery object and method in Java belongs to a class • Classes have data (fields) and code (methods) andClasses have data (fields) and code (methods) and classes (member classes or inner classes)classes (member classes or inner classes) • Static methods and fields belong to the class itselfStatic methods and fields belong to the class itself • Others belong to instancesOthers belong to instances
  • 4. An example of a classAn example of a class class Person { Variable String name; int age; Method void birthday ( ) { age++; System.out.println (name + ' is now ' + age); } }
  • 5. ScopingScoping As in C/C++, scope is determined by the placement of curly braces {}.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.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.
  • 6. Scope of ObjectsScope of Objects • Java objects don’t have the same lifetimes asJava objects don’t have the same lifetimes as primitives.primitives. • When you create a Java object usingWhen you create a Java object using newnew, it, it hangs around past the end of the scope.hangs around past the end of the scope. • Here, the scope of name s is delimited by the {}sHere, the scope of name s is delimited by the {}s but the String object hangs around until GC’dbut the String object hangs around until GC’d {{ String s = newString s = new String("aString("a string");string"); } /* end of scope */} /* end of scope */
  • 7. TheThe staticstatic keywordkeyword • Java methods and variables can be declared staticJava methods and variables can be declared static • These existThese exist independent of any objectindependent of any object • This means that a Class’sThis means that a Class’s – static methods can be calledstatic methods can be called even if no objects of thateven if no objects of that class have been created andclass have been created and – static data is “shared” by all instances (i.e., one rvaluestatic data is “shared” by all instances (i.e., one rvalue per class instead of one per instanceper 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
  • 8. ExampleExample public class Circle {public class Circle { // A class field// A class field public static final double PI= 3.14159; // A usefulpublic static final double PI= 3.14159; // A useful constantconstant // A class method: just compute a value based on the// A class method: just compute a value based on the argumentsarguments public static double radiansToDegrees(double rads) {public static double radiansToDegrees(double rads) { return rads * 180 / PI;return rads * 180 / PI; }} // An instance field// An instance field public double r; // The radius of thepublic double r; // The radius of the circlecircle // Two methods which operate on the instance fields of// Two methods which operate on the instance fields of an objectan object public double area() { // Compute the area ofpublic double area() { // Compute the area of the circlethe circle return PI * r * r;return PI * r * r; }} public double circumference() { // Compute thepublic double circumference() { // Compute the circumference of the circlecircumference of the circle return 2 * PI * r;return 2 * PI * r; }} }}
  • 9. Array OperationsArray Operations • Subscripts always start at 0 as in CSubscripts always start at 0 as in C • Subscript checking is done automaticallySubscript checking is done automatically • Certain operations are defined on arraysCertain operations are defined on arrays of objects, as for other classesof objects, as for other classes – e.g. myArray.length == 5e.g. myArray.length == 5
  • 10. An array is an objectAn array is an object • Person mary = new Person ( );Person mary = new Person ( ); • int myArray[ ] = new int[5];int myArray[ ] = new int[5]; • int myArray[ ] = {1, 4, 9, 16, 25};int myArray[ ] = {1, 4, 9, 16, 25}; • String languages [ ] = {"Prolog", "Java"};String languages [ ] = {"Prolog", "Java"}; • Since arrays are objects they are allocated dynamicallySince arrays are objects they are allocated dynamically • Arrays, like all objects, are subject to garbage collectionArrays, like all objects, are subject to garbage collection when no more references remainwhen no more references remain – so fewer memory leaksso fewer memory leaks – Java doesn’t have pointers!Java doesn’t have pointers!
  • 12. NSIT ,JetalpurNSIT ,Jetalpur 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
  • 13. NSIT ,JetalpurNSIT ,Jetalpur Factorial ExampleFactorial Example /* This program computes the factorial of a number/* This program computes the factorial of a number */*/ public class Factorial { // Define a classpublic class Factorial { // Define a class public static void main(String[] args) { // The program startspublic static void main(String[] args) { // The program starts herehere int input = Integer.parseInt(args[0]); // Get the user'sint input = Integer.parseInt(args[0]); // Get the user's inputinput double result = factorial(input); // Compute thedouble result = factorial(input); // Compute the factorialfactorial System.out.println(result); // Print out theSystem.out.println(result); // Print out the resultresult } // The main() method} // The main() method ends hereends here public static double factorial(int x) { // This methodpublic static double factorial(int x) { // This method computes x!computes x! if (x < 0) // Check for bad inputif (x < 0) // Check for bad input return 0.0; // if bad, return 0return 0.0; // if bad, return 0 double fact = 1.0; // Begin with andouble fact = 1.0; // Begin with an initial valueinitial value while(x > 1) { // Loop until x equalswhile(x > 1) { // Loop until x equals fact = fact * x; // multiply by xfact = fact * x; // multiply by x each timeeach time x = x - 1; // and thenx = x - 1; // and then decrement xdecrement x
  • 14. NSIT ,JetalpurNSIT ,Jetalpur ConstructorsConstructors • Classes should define one or more methods to createClasses should define one or more methods to create or construct instances of the classor construct instances of the class • Their name is the same as the class nameTheir name is the same as the class name – note deviation from convention that methods begin withnote deviation from convention that methods begin with lower caselower case • Constructors are differentiated by the number andConstructors are differentiated by the number and types of their argumentstypes of their arguments – An example of overloadingAn example of overloading • If you don’t define a constructor, a default one will beIf you don’t define a constructor, a default one will be created.created. • Constructors automatically invoke the zero argumentConstructors automatically invoke the zero argument constructor of their superclass when they begin (noteconstructor of their superclass when they begin (note that this yields a recursive process!)that this yields a recursive process!)
  • 15. Methods, arguments andMethods, arguments and return valuesreturn values • Java methods are like C/C++ functions.Java methods are like C/C++ functions. General case:General case: returnTypereturnType methodNamemethodName (( arg1arg1,, arg2arg2, …, … argNargN)) {{ methodBodymethodBody }} The return keyword exits a method optionally with a valueThe return keyword exits a method optionally with a value int storage(String s) {return s.length() * 2;}int storage(String s) {return s.length() * 2;} boolean flag() { return true; }boolean flag() { return true; } float naturalLogBase() { return 2.718f; }float naturalLogBase() { return 2.718f; } void nothing() { return; }void nothing() { return; } void nothing2() {}void nothing2() {}