SlideShare a Scribd company logo
NSIT ,JetalpurNSIT ,Jetalpur
CORECORE JAVAJAVA
CONCEPTSCONCEPTS
SURABHISURABHI MISHRAMISHRA
(LCE)(LCE)
NSITNSIT
NSIT ,Jetalpur
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
*/
NSIT ,Jetalpur
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
NSIT ,Jetalpur
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);
}
}
NSIT ,Jetalpur
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.
NSIT ,Jetalpur
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 */
NSIT ,Jetalpur
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
NSIT ,Jetalpur
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;
}}
}}
NSIT ,Jetalpur
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
NSIT ,Jetalpur
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!
NSIT ,Jetalpur
ExampleExample
ProgramsPrograms
NSIT ,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 ,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 ,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!)
NSIT ,Jetalpur
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 (20)

PDF
Procedure Typing for Scala
akuklev
 
PDF
Scala test
Inphina Technologies
 
PPT
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
PPT
Java Tutorials
Woxa Technologies
 
PPT
core java
Vinodh Kumar
 
PPT
java training faridabad
Woxa Technologies
 
PPT
Java02
Vinod siragaon
 
PDF
Java Day-5
People Strategists
 
PPT
Java Tut1
guest5c8bd1
 
ODP
Synapseindia reviews.odp.
Tarunsingh198
 
PPT
Java 5 Features
sholavanalli
 
PPTX
Java best practices
Անուշիկ Միրզոյան
 
PPT
Java tutorials
saryu2011
 
PDF
Java Day-4
People Strategists
 
PDF
OOPs & Inheritance Notes
Shalabh Chaudhary
 
ODP
Functional Objects & Function and Closures
Sandip Kumar
 
PDF
Built in classes in java
Mahmoud Ali
 
PPTX
About Python
Shao-Chuan Wang
 
PDF
Workshop Scala
Bert Van Vreckem
 
Procedure Typing for Scala
akuklev
 
Java tutorial for Beginners and Entry Level
Ramrao Desai
 
Java Tutorials
Woxa Technologies
 
core java
Vinodh Kumar
 
java training faridabad
Woxa Technologies
 
Java Day-5
People Strategists
 
Java Tut1
guest5c8bd1
 
Synapseindia reviews.odp.
Tarunsingh198
 
Java 5 Features
sholavanalli
 
Java best practices
Անուշիկ Միրզոյան
 
Java tutorials
saryu2011
 
Java Day-4
People Strategists
 
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Functional Objects & Function and Closures
Sandip Kumar
 
Built in classes in java
Mahmoud Ali
 
About Python
Shao-Chuan Wang
 
Workshop Scala
Bert Van Vreckem
 

Similar to Core java concepts (20)

PPT
Java Concepts
AbdulImrankhan7
 
PPT
Core java concepts
javeed_mhd
 
PPT
Core Java
Khasim Saheb
 
PPT
Best Core Java Training In Bangalore
rajkamaltibacademy
 
PPT
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
PPTX
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
PPTX
Java assignment help
Jacob William
 
PPTX
Hemajava
SangeethaSasi1
 
PPT
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
PPTX
Java basics
Shivanshu Purwar
 
PDF
03_Objects and Classes in java.pdf
Parameshwar Maddela
 
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
PPT
Defining classes-and-objects-1.0
BG Java EE Course
 
PPT
Java Basics
F K
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PPTX
Class and Object.pptx from nit patna ece department
om2348023vats
 
PPTX
Chapter 8 java
Ahmad sohail Kakar
 
PPT
Lecture 2 classes i
the_wumberlog
 
PPT
java02.pptsatrrhfhf https://www.slideshare.net/slideshow/java-notespdf-259708...
atharvtayde5632
 
PPT
Ap Power Point Chpt4
dplunkett
 
Java Concepts
AbdulImrankhan7
 
Core java concepts
javeed_mhd
 
Core Java
Khasim Saheb
 
Best Core Java Training In Bangalore
rajkamaltibacademy
 
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Java assignment help
Jacob William
 
Hemajava
SangeethaSasi1
 
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
Java basics
Shivanshu Purwar
 
03_Objects and Classes in java.pdf
Parameshwar Maddela
 
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Defining classes-and-objects-1.0
BG Java EE Course
 
Java Basics
F K
 
Classes, objects in JAVA
Abhilash Nair
 
Class and Object.pptx from nit patna ece department
om2348023vats
 
Chapter 8 java
Ahmad sohail Kakar
 
Lecture 2 classes i
the_wumberlog
 
java02.pptsatrrhfhf https://www.slideshare.net/slideshow/java-notespdf-259708...
atharvtayde5632
 
Ap Power Point Chpt4
dplunkett
 
Ad

Core java concepts

  • 1. NSIT ,JetalpurNSIT ,Jetalpur CORECORE JAVAJAVA CONCEPTSCONCEPTS SURABHISURABHI MISHRAMISHRA (LCE)(LCE) NSITNSIT
  • 2. NSIT ,Jetalpur 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. NSIT ,Jetalpur 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. NSIT ,Jetalpur 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. NSIT ,Jetalpur 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. NSIT ,Jetalpur 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. NSIT ,Jetalpur 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. NSIT ,Jetalpur 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. NSIT ,Jetalpur 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. NSIT ,Jetalpur 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 ,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 ,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 ,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. NSIT ,Jetalpur 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() {}