SlideShare a Scribd company logo
Slide 1
Core Java
Lesson 1: Introduction to Java
Slide 2
● Introduction to Java
● Features of Java
● Evolution of Java
● Developing software in Java
● Writing, Compiling and execution of Simple Java Program
● Java Language Fundamentals
Lesson Objective
Slide 3
● History of Java :
Developed: 1991 - Part of Sun's "Green Team Project
Created by: Patrick Naughton, Mike Sheridan, and James Gosling
Demo released: 1992
Released: 1995
Original name: Oak
● Recent News:
* 2006 – Sun released much of java as open source software
* 2009 – 2010 – Oracle corporation acquired Sun Microsystems
● About Java Technology:
Java is a high level programming language created by Sun Microsystems.
Java technology is both a programming language and a platform
Introduction to Java
Slide 4
● Object Oriented : class, object, inheritance, polymorphism … etc
● Simple : easy to learn
● Robust : strongly typed
● Secure : Byte code verifier, Security Manager …etc.
● Architecture Neutral: Platform independent
● Interpreted and Compiled
● Multithreaded: Concurrent running tasks
● Dynamic : run time linking of code [applet]
● Memory Management and Garbage Collection
Features of Java
Slide 5
● Java Development Kit(JDK)
The Java Developer’s Kit is distributed by Sun Microsystems. The JDK
contains documentation, examples, installation instructions, class
libraries packages and tools.
There are two installers available.
● JDK – Software development Kit – compile and run java program
● JRE – Java Runtime Environment – run java program [subset of JDK ]
● How to Install Java?
● Download the latest Java Installable from
http://www.oracle.com/technetwork/java/javase/downloads/index.html
● Java Virtual Machine (JVM) : Platform Independent
Developing software in Java
Slide 6
● Java Virtual Machine (JVM)
● Java VM is available on many different operating systems. Hence the same
.class files can be run on Microsoft Windows, the Solaris TM Operating System
(Solaris OS), Linux, or Mac OS.
Writing, Compiling and Execution of Java Program
Slide 7
● A Java program is written, compiled and executed in three steps.
● Step – 1: The source code is written in plain text file ending with .java
extension.
● Step – 2 : The source files are compiled into .class files using javac compiler.
● Step – 3: The java launcher tool runs the application with an instance of JVM -
Java Virtual Machine.
Writing, Compiling and Execution of Java Program
Slide 8
● A Simple Java Program
class ExampleProgram {
public static void main(String[] args){
System.out.println("I'm a Simple Program");
}
}
● Compiling the Program
javac ExampleProgram.java
● Interpreting and Running the Program
Once the program successfully compiles into Java bytecodes, the
Java interpreter is invoked at the command line on Unix and DOS shell
operating systems as follows:
java ExampleProgram
● Output : I'm a Simple Program
Writing, Compiling and Execution of Java Program
Slide 9
● Java Comments
● Single line Comment // comment statement
● Multiline Comment /* comment statement 1
comment statement 2
*/
Java Language Fundamentals
/* This Java class example describes how class is defined and being used in
Java language.
*/
public class JavaClassExample {
//main method – Entry Point
public static void main(String args[]){
//method call
System.out.println(“Hello World”);
}
}
OUTPUT : Hello World
Slide 10
Java Comments
● Comments :
Comments are descriptions that are added to a program to make code
easier to understand. The compiler ignores comments and hence its only for
documentation of the program. Java supports three comment styles.
● Implementation Comments:
Line style comments - begin with // and terminate at the end of the line.
Block style comments - begin with /* and terminate with */ that spans multiple
lines.
● Documentation comments
Begin with /** and terminate with */ that spans multiple lines. They
are generally created using the automatic documentation generation tool,
such as javadoc.
Slide 11
Type Size/Format Description
byte 8-bit Byte-length integer
short 16-bit Short Integer
int 32-bit Integer
long 64-bit Long Integer
float 32-bit IEEE 754 Single precision floating point
double 64-bit IEE 754 Double precision floating point
char 16-bit A single character
boolean 1-bit True or False
Data Types
● Variables have a data type, that indicates the kind of value they
can store.
Slide 12
● Basic storage in a Java program
● Three types of variables:
● Instance variables
 Instantiated for every object of the class.
● Static variables
 Class Variables
 Not instantiated for every object of the class.
● Local variables
 Declared in methods and blocks.
● Formal Parameters: Arguments passed to a function.
Types of Variables
Slide 13
class emp {
String name; //Instance Variable
int empcode; //Instance Variable
float basicsalary; //Instance Variable
static int obcount; //static variable
void calculateSalary() {
float temp sal; //Local variable
….
}
} //class emp ends
Types of Variables
Slide 14
● Parameters or arguments passed to a function are
passed by value for primitive data-types.
● Parameters or arguments passed to a function are passed by
reference for non-primitive data-types
● Example: All Java objects.
Methods and Parameter Passing
void myFunction(Integer a) {
a++;
System.out.println(a);
}
….
Integer x = 45;
System.out.println(x);
myFunction(x);
System.out.println(x);
Output is, “45 46 45”
void myFunction(int a) {
a++;
System.out.println(a);
}
….
int x = 45;
System.out.println(x);
myFunction(x);
System.out.println(x);
Output is, “45 46 45”
Slide 15
● New feature added in J2SE5.0.
● Allows methods to receive unspecified number of arguments.
● An argument type followed by ellipsis(…) indicates variable number
of arguments of a particular type.
● Variable-length argument can take from zero to n arguments.
● Ellipsis can be used only once in the parameter list.
● Ellipsis must be placed at the end of the parameter list.
Variable Argument List
Slide 16
● Valid Code
void print(int a,int y,String...s)
{
//code
}
print(1,1,”XYZ”) or print(2,5) or print(5,6,”A”,”B”) invokes
the above print function
● Invalid Code
void print(int a, int b…,float c)
{
//code
}
Variable Argument List
Slide 17
Demo:
● varargs.java
Demo : Variable Argument List
Slide 18
Keywords in Java
* not used *** added in 1.4
** added in 1.2 **** added in 5.0
● Keywords are reserved words can’t be used as variables, function
and class names.
Slide 19
● Operators can be divided into following groups:
● Arithmetic
● Bitwise
● Relational
● Logical
● instanceOf Operator
Operators and Assignments Java
Slide 20
Arithmetic Operators
Slide 21
● Apply upon int, long, short, char and byte data types:
Bitwise Operators
Slide 22
● Determine the relationship that one operand has to another.
● Ordering and equality.
Relational Operators
Slide 23
Logical Operators
Slide 24
● The instanceof operator compares an object to a specified
type
● Checks whether an object is:
● An instance of a class.
● An instance of a subclass.
● An instance of a class that implements a particular interface.
● The following returns true:
new String("Hello") instanceof String;
instanceOf Operators
Slide 25
● Use control flow statements to:
● Conditionally execute statements.
● Repeatedly execute a block of statements.
● Change the normal, sequential flow of control.
● Categorized into two types:
● Selection Statements
● Iteration Statements
Control Statements
Slide 26
● Allows programs to choose between alternate actions on execution.
● “If” used for conditional branch:
if (condition) statement1;
else statement2;
● “Switch” used as an alternative to multiple “if’s”:
switch(expression){
case value1: //statement sequence
break;
case value2: //statement sequence
break; …
default: //default statement sequence
}
Selection Statements
Slide 27
● Allow a block of statements to execute repeatedly.
● While Loop:
● Enters the loop if the condition is true.
while (condition)
{ //body of loop }
● Do – While Loop:
● Loop executes at least once even if the condition is false.
do
{ //body of the loop
} while(condition)
● For Loop: for( initialization ; condition ; iteration)
{ //body of the loop }
Iteration Statements
Slide 28
● New feature introduced in Java 5.
● Iterate through a collection or array.
● Syntax:
for (variable : collection)
{ //code}
● Example
int sum(int[] a)
{
int result = 0;
for (int i : a)
result += i;
return result; }
Enhanced for Loop (foreach)
Slide 29
● Classes:
● A template for multiple objects with similar features.
● A blueprint or the definition of objects.
class < class_name>
{
type var1; …
Type method_name(arguments )
{
body
} …
} //class ends
● Objects:
● Instance of a class.
● Concrete representation of class.
Objects and Classes
Slide 30
Introduction to Classes
● Code Snippet:
class Box{
double width;
double height;
double depth;
double volume()
{
return width*height*depth;
} //method volume ends.
}//class box ends.
Slide 31
Declaring Objects
● Code Snippet
class Impl{
public static void main(String a[])
{
//declare a reference to object
Box b;
//allocate a memory for box object.
b = new Box();
// call a method on that object.
b.volume();
}
}
Slide 32
● A Java package is a set of classes which are grouped together.
● To organize Java classes
● To code multiple Java classes with the same name.
● Using Java Packages :
To use a package in your Java source code, you must either import
the package or use the fully qualified class name each time you
use a class.
● Importing Classes :
import java.util.Date;
Or
Java.util.Date d = new java.util.Date();
All the classes in Java.lang package are automatically imported when
the program runs. The rest of other classes in the packages are to
be imported by the programmer by using the import keyword.
Packages in Java
Slide 33
Demo:
Box.java
Demo: Creating Objects and classes
Slide 34
Constructors
● Constructors are similar to methods except that constructors have the same name
as the class . When a new instance (a new object) of a class is created using the
new keyword, the constructor for that class is called. Constructors are used to
initialize the instance variables (fields) of an object.
● Default constructor. If we don't define a constructor for a class, a default
parameterless constructor is automatically created by the compiler. The default
constructor calls the default parent constructor (super()) and initializes all instance
variables to default value (zero for numeric types, null for object references, and
false for booleans).
● Default constructor is created only if there are no constructors. If you define
any constructor for your class, no default constructor is automatically created.
● Differences between methods and constructors.
● Constructor does not have a return type
● There is no return statement in the body of the constructor.
● The first line of a constructor must either be a call on another constructor in
the same class (using this), or a call on the superclass constructor (using
super). If the first line is neither of these, the compiler automatically inserts a
call to the parameterless super class constructor.
Slide 35
Constructor – Example program
Example of explicit this constructor call
public class Point {
int m_x;
int m_y;
//============ Constructor public
Point(int x, int y) {
m_x = x;
m_y = y;
}
//============ Parameterless default constructor
public Point() {
this(0, 0);
// Calls other constructor.
}
. . . }
Slide 36
Types of Class Members
● Default access members (No access specifier)
● accessible only by classes in the same package
● Private members
● cannot be accesses by anywhere outside the enclosing class
● Public members
● are visible to any class in the Java program, whether these classes
are in the same package or in another package.
● Protected member
● only accessible by subclasses in same aa well as other packages
Slide 37
● Dynamic and Automatic
● No Delete operator
● Java Virtual Machine (JVM) de-allocates memory allocated to
unreferenced objects during the garbage collection process.
Memory Management
Slide 38
● Garbage Collector:
● Lowest Priority Daemon Thread
● Runs in the background when JVM starts.
● Collects all the unreferenced objects.
● Frees the space occupied by these objects.
● Call System.gc() method to “hint” the JVM to invoke the garbage
collector.
 There is no guarantee that it would be invoked. It is implementation
dependent.
Enhancement in Garbage Collector
Slide 39
● All Java classes have constructors.
● Constructors initialize a new object of that type.
● Default no-argument constructor is provided if program has no
constructors.
● Constructors:
 Same name as the class.
 No return type; not even void.
Memory Management
Slide 40
● Memory is automatically de-allocated in Java.
● Invoke finalize() to perform some housekeeping tasks before an
object is garbage collected.
● Invoked just before the garbage collector runs:
● protected void finalize()
Finalize() Method
Slide 41
● A group of like-typed variables referred by a common name.
● Array declaration:
● int arr [];
arr = new int[10]
● int arr[] = {2,3,4,5};
● int two_d[][] = new int[4][5];
Arrays
Slide 42
● Arrays of objects too can be created:
● Example 1:
 Box Barr[] = new Box[3];
 Barr[0] = new Box();
 Barr[1] = new Box();
 Barr[2] = new Box();
● Example 2:
 String[] Words = new String[2];
 Words[0]=new String(“Bombay”);
 Words[1]=new String(“Pune”);
Creating Array Objects
Slide 43
● Arrays of objects too can be created:
● Example 1:
 Box Barr[] = new Box[3];
 Barr[0] = new Box();
 Barr[1] = new Box();
 Barr[2] = new Box();
● Example 2:
 String[] Words = new String[2];
 Words[0]=new String(“Bombay”);
 Words[1]=new String(“Pune”);
Creating Array Objects
Slide 44
Demo: ArrayDemo.java
Demo : Creating Array Objects
Slide 45
Static variable
● Static variable is shared by all the class members.
● Used independently of objects of that class.
● Static members can be accessed before an object of a class is
created, by using the class name:
●Example:
static int intNum1 = 3;
Slide 46
4646
Static Methods
● Restrictions:
●Can only call other static methods.
●Must only access other static data.
●Cannot refer to this or super in any way.
●Can not access non-static variables and methods directly:
 Explicit instance variables should be made available to the method.
 Method main() is a static method. It is called by JVM.
Slide 47
● Cosmic super class.
● Ultimate ancestor
● Every class in Java implicitly extends Object.
● Object type variables can refer to objects of any type:
● Example:
Object obj = new Emp();
● Object Class Methods:
● void finalize()
● Class getClass()
● String toString()
The Object Class
Slide 48
Object Class Methods
Slide 49
● Used to interact with any of the system resources.
● Cannot be instantiated.
● Contains a methods and variables to handle system I/O.
● Facilities provided by the System class:
● Standard input
● Standard output
● Error output streams
The System Class
Slide 50
The System Class (contd..)
Slide 51
Demo: Elapsed.java
Demo : The System Class
Slide 52
● String is handled as an object of class String and not as an array of
characters.
● String class is a better and a convenient way to handle any
operation.
● One main restriction is that once an object of this class is created,
the contents cannot be changed.
String Handling
Slide 53
String Handling – Important Methods
● length(): length of string.
● indexOf(): searches an occurrence of a char, or string within other
string.
● substring(): Retrieves substring from the object.
● trim(): Removes spaces.
● valueOf(): Converts data to string.
Slide 54
The String Class
str1
String str = new String(“Pooja”);
String str1 = new String(“Sam”);
Pooja
Sam
str
str1
String str = new String(“Pooja”);
String str1 = str;
Pooja str
Heap Stack
Slide 55
● Use a “+” sign to concatenate two strings:
● String Subject = "Core " + "Java"; -> Core Java
● String concatenation operator if one operand is a string:
 String a = "String"; int b = 3; int c=7
 System.out.println(a + b + c); -> String37
● Addition operator if both operands are numbers:
 System.out.println(a + (b + c)); -> String10
String Concatenation
Slide 56
● public String concat(String s)
● Used to concatenate a string to an existing string.
● String x = "Core ";
● System.out.println( x=x.concat(" Java") );
● Output -> "Core Java”
String Concatenation (contd..)
Slide 57
class EqualsNotEqualTo {
public static void main(String args[]) {
String str1 = "Hello";
String str2 = new String(str1);
System.out.println(str1 + " equals " + str2 + " -> " +
str1.equals(str2));
System.out.println(str1 + " == " + str2 + " -> " + (str1 ==str2));
}
}
Output : Hello equals Hello -> true
Hello == Hello -> false
String Comparison
Slide 58
● Use the following to make ample modifications to character
strings:
● java.lang.StringBuffer
● java.lang.StringBuilder
● Many string object manipulations end up with a many abandoned
string objects in the String pool
● String Objects are immutable.
StringBuffer sb = new StringBuffer("abc");
sb.append("def");
System.out.println("sb = " + sb); // output is "sb = abcdef"
StringBuffer Class
Slide 59
● Added in Java 5.
● Exactly the same API as the StringBuffer class, except:
● It is not thread safe.
● It runs faster than StringBuffer.
StringBuilder sb = new StringBuilder("abc");
sb.append("def").reverse().insert(3, "---");
System.out.println( sb ); // output is "fed---cba"
StringBuilder Class
Slide 60
Demo:
SimpleString.java
ToStringDemo.java
StringBufferDemo.java
CharDemo.java
Demo : String handling
Slide 61
● Correspond to primitive data types in Java.
● Represent primitive values as objects.
● Wrapper objects are immutable.
Wrapper Classes
Slide 62
● Casting operator converts one variable value to another where two
variables correspond to two different data types.
variable1 = (variable1) variable2
● Here, variable2 is typecast to variable1.
● Data type can either be a reference type or a primitive one.
Casting for Conversion of Data type
Slide 63
● When one type of data is assigned to another type of variable,
automatic type conversion takes place if:
● Both types are compatible.
● Destination type is larger than the source type.
● No explicit casting is needed (widening conversion).
int a=5; float b; b=a;
● If there is a possibility of data loss, explicit cast is needed:
int i = (int) (5.6/2/7);
Casting Between Primitive Types
Slide 64
● One class types involved must be the same class or a subclass of
the other class type.
● Assignment to different class types is allowed only if a value of the
class type is assigned to a variable of its superclass type.
● Assignment to a variable of the subclass type needs explicit
casting:
String StrObj = Obj;
● Explicit casting is not needed for the following:
String StrObj = new String(“Hello”);
Object Obj = StrObj;
Casting Between Reference Types
Slide 65
● Two types of reference variable castings:
● Downcasting:
Object Obj = new Object ( );
String StrObj = (String) Obj;
● Upcasting:
String StrObj = new String(“Hello”);
Object Obj = StrObj;
Casting Between Reference Types (contd..)

More Related Content

What's hot

Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
Math-Circle
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
Hitesh-Java
 
Arrays in Java
Arrays in Java Arrays in Java
Arrays in Java
Hitesh-Java
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
Sandeep Rawat
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
Eduonix Learning Solutions
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
Surbhi Panhalkar
 
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
Lokesh Kakkar Mobile No. 814-614-5674
 
Java Introduction
Java IntroductionJava Introduction
Java Introduction
sunmitraeducation
 
Java Basic Oops Concept
Java Basic Oops ConceptJava Basic Oops Concept
Java Basic Oops Concept
atozknowledge .com
 
Java
JavaJava
Java
s4al_com
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Anjan Mahanta
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
Mahika Tutorials
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
ParminderKundu
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Edureka!
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
gebrsh
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
Abir Mohammad
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Java seminar
Java seminarJava seminar
Java seminar
devendrakhairwa
 
Intro to Java
Intro to JavaIntro to Java
Intro to Java
karianneban
 

What's hot (20)

Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Arrays in Java
Arrays in Java Arrays in Java
Arrays in Java
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
 
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
 
Java Introduction
Java IntroductionJava Introduction
Java Introduction
 
Java Basic Oops Concept
Java Basic Oops ConceptJava Basic Oops Concept
Java Basic Oops Concept
 
Java
JavaJava
Java
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java seminar
Java seminarJava seminar
Java seminar
 
Intro to Java
Intro to JavaIntro to Java
Intro to Java
 

Similar to Core Java Tutorial

Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
PravinYalameli
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
divaskrgupta007
 
Java introduction
Java introductionJava introduction
Java introduction
Migrant Systems
 
What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)
Moaid Hathot
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
Java intro
Java introJava intro
Java intro
husnara mohammad
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
Partnered Health
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
Francesco Nolano
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
Shaharyar khan
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
SadhanaParameswaran
 
Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
Gabor Paller
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
AssignmentjsnsnshshusjdnsnshhzudjdndndjdAssignmentjsnsnshshusjdnsnshhzudjdndndjd
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
tusharjain613841
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
Jonathan Fine
 
Java introduction
Java introductionJava introduction
Java introduction
logeswarisaravanan
 
Java Standard edition(Java ) programming Basics for beginner's
Java Standard edition(Java ) programming Basics  for beginner'sJava Standard edition(Java ) programming Basics  for beginner's
Java Standard edition(Java ) programming Basics for beginner's
momin6
 
java
javajava
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topics
Rajesh Verma
 
Java vs .Net
Java vs .NetJava vs .Net
Java vs .Net
Tejasvi Rastogi
 

Similar to Core Java Tutorial (20)

Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
Java introduction
Java introductionJava introduction
Java introduction
 
Unit 1
Unit 1Unit 1
Unit 1
 
What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)What's coming to c# (Tel-Aviv, 2018)
What's coming to c# (Tel-Aviv, 2018)
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
Java intro
Java introJava intro
Java intro
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
 
Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
AssignmentjsnsnshshusjdnsnshhzudjdndndjdAssignmentjsnsnshshusjdnsnshhzudjdndndjd
Assignmentjsnsnshshusjdnsnshhzudjdndndjd
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java Standard edition(Java ) programming Basics for beginner's
Java Standard edition(Java ) programming Basics  for beginner'sJava Standard edition(Java ) programming Basics  for beginner's
Java Standard edition(Java ) programming Basics for beginner's
 
java
javajava
java
 
Shiksharth com java_topics
Shiksharth com java_topicsShiksharth com java_topics
Shiksharth com java_topics
 
Java vs .Net
Java vs .NetJava vs .Net
Java vs .Net
 

Recently uploaded

Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
EduSkills OECD
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 

Recently uploaded (20)

Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxStudents, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 

Core Java Tutorial

  • 1. Slide 1 Core Java Lesson 1: Introduction to Java
  • 2. Slide 2 ● Introduction to Java ● Features of Java ● Evolution of Java ● Developing software in Java ● Writing, Compiling and execution of Simple Java Program ● Java Language Fundamentals Lesson Objective
  • 3. Slide 3 ● History of Java : Developed: 1991 - Part of Sun's "Green Team Project Created by: Patrick Naughton, Mike Sheridan, and James Gosling Demo released: 1992 Released: 1995 Original name: Oak ● Recent News: * 2006 – Sun released much of java as open source software * 2009 – 2010 – Oracle corporation acquired Sun Microsystems ● About Java Technology: Java is a high level programming language created by Sun Microsystems. Java technology is both a programming language and a platform Introduction to Java
  • 4. Slide 4 ● Object Oriented : class, object, inheritance, polymorphism … etc ● Simple : easy to learn ● Robust : strongly typed ● Secure : Byte code verifier, Security Manager …etc. ● Architecture Neutral: Platform independent ● Interpreted and Compiled ● Multithreaded: Concurrent running tasks ● Dynamic : run time linking of code [applet] ● Memory Management and Garbage Collection Features of Java
  • 5. Slide 5 ● Java Development Kit(JDK) The Java Developer’s Kit is distributed by Sun Microsystems. The JDK contains documentation, examples, installation instructions, class libraries packages and tools. There are two installers available. ● JDK – Software development Kit – compile and run java program ● JRE – Java Runtime Environment – run java program [subset of JDK ] ● How to Install Java? ● Download the latest Java Installable from http://www.oracle.com/technetwork/java/javase/downloads/index.html ● Java Virtual Machine (JVM) : Platform Independent Developing software in Java
  • 6. Slide 6 ● Java Virtual Machine (JVM) ● Java VM is available on many different operating systems. Hence the same .class files can be run on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS. Writing, Compiling and Execution of Java Program
  • 7. Slide 7 ● A Java program is written, compiled and executed in three steps. ● Step – 1: The source code is written in plain text file ending with .java extension. ● Step – 2 : The source files are compiled into .class files using javac compiler. ● Step – 3: The java launcher tool runs the application with an instance of JVM - Java Virtual Machine. Writing, Compiling and Execution of Java Program
  • 8. Slide 8 ● A Simple Java Program class ExampleProgram { public static void main(String[] args){ System.out.println("I'm a Simple Program"); } } ● Compiling the Program javac ExampleProgram.java ● Interpreting and Running the Program Once the program successfully compiles into Java bytecodes, the Java interpreter is invoked at the command line on Unix and DOS shell operating systems as follows: java ExampleProgram ● Output : I'm a Simple Program Writing, Compiling and Execution of Java Program
  • 9. Slide 9 ● Java Comments ● Single line Comment // comment statement ● Multiline Comment /* comment statement 1 comment statement 2 */ Java Language Fundamentals /* This Java class example describes how class is defined and being used in Java language. */ public class JavaClassExample { //main method – Entry Point public static void main(String args[]){ //method call System.out.println(“Hello World”); } } OUTPUT : Hello World
  • 10. Slide 10 Java Comments ● Comments : Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program. Java supports three comment styles. ● Implementation Comments: Line style comments - begin with // and terminate at the end of the line. Block style comments - begin with /* and terminate with */ that spans multiple lines. ● Documentation comments Begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc.
  • 11. Slide 11 Type Size/Format Description byte 8-bit Byte-length integer short 16-bit Short Integer int 32-bit Integer long 64-bit Long Integer float 32-bit IEEE 754 Single precision floating point double 64-bit IEE 754 Double precision floating point char 16-bit A single character boolean 1-bit True or False Data Types ● Variables have a data type, that indicates the kind of value they can store.
  • 12. Slide 12 ● Basic storage in a Java program ● Three types of variables: ● Instance variables  Instantiated for every object of the class. ● Static variables  Class Variables  Not instantiated for every object of the class. ● Local variables  Declared in methods and blocks. ● Formal Parameters: Arguments passed to a function. Types of Variables
  • 13. Slide 13 class emp { String name; //Instance Variable int empcode; //Instance Variable float basicsalary; //Instance Variable static int obcount; //static variable void calculateSalary() { float temp sal; //Local variable …. } } //class emp ends Types of Variables
  • 14. Slide 14 ● Parameters or arguments passed to a function are passed by value for primitive data-types. ● Parameters or arguments passed to a function are passed by reference for non-primitive data-types ● Example: All Java objects. Methods and Parameter Passing void myFunction(Integer a) { a++; System.out.println(a); } …. Integer x = 45; System.out.println(x); myFunction(x); System.out.println(x); Output is, “45 46 45” void myFunction(int a) { a++; System.out.println(a); } …. int x = 45; System.out.println(x); myFunction(x); System.out.println(x); Output is, “45 46 45”
  • 15. Slide 15 ● New feature added in J2SE5.0. ● Allows methods to receive unspecified number of arguments. ● An argument type followed by ellipsis(…) indicates variable number of arguments of a particular type. ● Variable-length argument can take from zero to n arguments. ● Ellipsis can be used only once in the parameter list. ● Ellipsis must be placed at the end of the parameter list. Variable Argument List
  • 16. Slide 16 ● Valid Code void print(int a,int y,String...s) { //code } print(1,1,”XYZ”) or print(2,5) or print(5,6,”A”,”B”) invokes the above print function ● Invalid Code void print(int a, int b…,float c) { //code } Variable Argument List
  • 17. Slide 17 Demo: ● varargs.java Demo : Variable Argument List
  • 18. Slide 18 Keywords in Java * not used *** added in 1.4 ** added in 1.2 **** added in 5.0 ● Keywords are reserved words can’t be used as variables, function and class names.
  • 19. Slide 19 ● Operators can be divided into following groups: ● Arithmetic ● Bitwise ● Relational ● Logical ● instanceOf Operator Operators and Assignments Java
  • 21. Slide 21 ● Apply upon int, long, short, char and byte data types: Bitwise Operators
  • 22. Slide 22 ● Determine the relationship that one operand has to another. ● Ordering and equality. Relational Operators
  • 24. Slide 24 ● The instanceof operator compares an object to a specified type ● Checks whether an object is: ● An instance of a class. ● An instance of a subclass. ● An instance of a class that implements a particular interface. ● The following returns true: new String("Hello") instanceof String; instanceOf Operators
  • 25. Slide 25 ● Use control flow statements to: ● Conditionally execute statements. ● Repeatedly execute a block of statements. ● Change the normal, sequential flow of control. ● Categorized into two types: ● Selection Statements ● Iteration Statements Control Statements
  • 26. Slide 26 ● Allows programs to choose between alternate actions on execution. ● “If” used for conditional branch: if (condition) statement1; else statement2; ● “Switch” used as an alternative to multiple “if’s”: switch(expression){ case value1: //statement sequence break; case value2: //statement sequence break; … default: //default statement sequence } Selection Statements
  • 27. Slide 27 ● Allow a block of statements to execute repeatedly. ● While Loop: ● Enters the loop if the condition is true. while (condition) { //body of loop } ● Do – While Loop: ● Loop executes at least once even if the condition is false. do { //body of the loop } while(condition) ● For Loop: for( initialization ; condition ; iteration) { //body of the loop } Iteration Statements
  • 28. Slide 28 ● New feature introduced in Java 5. ● Iterate through a collection or array. ● Syntax: for (variable : collection) { //code} ● Example int sum(int[] a) { int result = 0; for (int i : a) result += i; return result; } Enhanced for Loop (foreach)
  • 29. Slide 29 ● Classes: ● A template for multiple objects with similar features. ● A blueprint or the definition of objects. class < class_name> { type var1; … Type method_name(arguments ) { body } … } //class ends ● Objects: ● Instance of a class. ● Concrete representation of class. Objects and Classes
  • 30. Slide 30 Introduction to Classes ● Code Snippet: class Box{ double width; double height; double depth; double volume() { return width*height*depth; } //method volume ends. }//class box ends.
  • 31. Slide 31 Declaring Objects ● Code Snippet class Impl{ public static void main(String a[]) { //declare a reference to object Box b; //allocate a memory for box object. b = new Box(); // call a method on that object. b.volume(); } }
  • 32. Slide 32 ● A Java package is a set of classes which are grouped together. ● To organize Java classes ● To code multiple Java classes with the same name. ● Using Java Packages : To use a package in your Java source code, you must either import the package or use the fully qualified class name each time you use a class. ● Importing Classes : import java.util.Date; Or Java.util.Date d = new java.util.Date(); All the classes in Java.lang package are automatically imported when the program runs. The rest of other classes in the packages are to be imported by the programmer by using the import keyword. Packages in Java
  • 34. Slide 34 Constructors ● Constructors are similar to methods except that constructors have the same name as the class . When a new instance (a new object) of a class is created using the new keyword, the constructor for that class is called. Constructors are used to initialize the instance variables (fields) of an object. ● Default constructor. If we don't define a constructor for a class, a default parameterless constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans). ● Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created. ● Differences between methods and constructors. ● Constructor does not have a return type ● There is no return statement in the body of the constructor. ● The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor.
  • 35. Slide 35 Constructor – Example program Example of explicit this constructor call public class Point { int m_x; int m_y; //============ Constructor public Point(int x, int y) { m_x = x; m_y = y; } //============ Parameterless default constructor public Point() { this(0, 0); // Calls other constructor. } . . . }
  • 36. Slide 36 Types of Class Members ● Default access members (No access specifier) ● accessible only by classes in the same package ● Private members ● cannot be accesses by anywhere outside the enclosing class ● Public members ● are visible to any class in the Java program, whether these classes are in the same package or in another package. ● Protected member ● only accessible by subclasses in same aa well as other packages
  • 37. Slide 37 ● Dynamic and Automatic ● No Delete operator ● Java Virtual Machine (JVM) de-allocates memory allocated to unreferenced objects during the garbage collection process. Memory Management
  • 38. Slide 38 ● Garbage Collector: ● Lowest Priority Daemon Thread ● Runs in the background when JVM starts. ● Collects all the unreferenced objects. ● Frees the space occupied by these objects. ● Call System.gc() method to “hint” the JVM to invoke the garbage collector.  There is no guarantee that it would be invoked. It is implementation dependent. Enhancement in Garbage Collector
  • 39. Slide 39 ● All Java classes have constructors. ● Constructors initialize a new object of that type. ● Default no-argument constructor is provided if program has no constructors. ● Constructors:  Same name as the class.  No return type; not even void. Memory Management
  • 40. Slide 40 ● Memory is automatically de-allocated in Java. ● Invoke finalize() to perform some housekeeping tasks before an object is garbage collected. ● Invoked just before the garbage collector runs: ● protected void finalize() Finalize() Method
  • 41. Slide 41 ● A group of like-typed variables referred by a common name. ● Array declaration: ● int arr []; arr = new int[10] ● int arr[] = {2,3,4,5}; ● int two_d[][] = new int[4][5]; Arrays
  • 42. Slide 42 ● Arrays of objects too can be created: ● Example 1:  Box Barr[] = new Box[3];  Barr[0] = new Box();  Barr[1] = new Box();  Barr[2] = new Box(); ● Example 2:  String[] Words = new String[2];  Words[0]=new String(“Bombay”);  Words[1]=new String(“Pune”); Creating Array Objects
  • 43. Slide 43 ● Arrays of objects too can be created: ● Example 1:  Box Barr[] = new Box[3];  Barr[0] = new Box();  Barr[1] = new Box();  Barr[2] = new Box(); ● Example 2:  String[] Words = new String[2];  Words[0]=new String(“Bombay”);  Words[1]=new String(“Pune”); Creating Array Objects
  • 44. Slide 44 Demo: ArrayDemo.java Demo : Creating Array Objects
  • 45. Slide 45 Static variable ● Static variable is shared by all the class members. ● Used independently of objects of that class. ● Static members can be accessed before an object of a class is created, by using the class name: ●Example: static int intNum1 = 3;
  • 46. Slide 46 4646 Static Methods ● Restrictions: ●Can only call other static methods. ●Must only access other static data. ●Cannot refer to this or super in any way. ●Can not access non-static variables and methods directly:  Explicit instance variables should be made available to the method.  Method main() is a static method. It is called by JVM.
  • 47. Slide 47 ● Cosmic super class. ● Ultimate ancestor ● Every class in Java implicitly extends Object. ● Object type variables can refer to objects of any type: ● Example: Object obj = new Emp(); ● Object Class Methods: ● void finalize() ● Class getClass() ● String toString() The Object Class
  • 49. Slide 49 ● Used to interact with any of the system resources. ● Cannot be instantiated. ● Contains a methods and variables to handle system I/O. ● Facilities provided by the System class: ● Standard input ● Standard output ● Error output streams The System Class
  • 50. Slide 50 The System Class (contd..)
  • 51. Slide 51 Demo: Elapsed.java Demo : The System Class
  • 52. Slide 52 ● String is handled as an object of class String and not as an array of characters. ● String class is a better and a convenient way to handle any operation. ● One main restriction is that once an object of this class is created, the contents cannot be changed. String Handling
  • 53. Slide 53 String Handling – Important Methods ● length(): length of string. ● indexOf(): searches an occurrence of a char, or string within other string. ● substring(): Retrieves substring from the object. ● trim(): Removes spaces. ● valueOf(): Converts data to string.
  • 54. Slide 54 The String Class str1 String str = new String(“Pooja”); String str1 = new String(“Sam”); Pooja Sam str str1 String str = new String(“Pooja”); String str1 = str; Pooja str Heap Stack
  • 55. Slide 55 ● Use a “+” sign to concatenate two strings: ● String Subject = "Core " + "Java"; -> Core Java ● String concatenation operator if one operand is a string:  String a = "String"; int b = 3; int c=7  System.out.println(a + b + c); -> String37 ● Addition operator if both operands are numbers:  System.out.println(a + (b + c)); -> String10 String Concatenation
  • 56. Slide 56 ● public String concat(String s) ● Used to concatenate a string to an existing string. ● String x = "Core "; ● System.out.println( x=x.concat(" Java") ); ● Output -> "Core Java” String Concatenation (contd..)
  • 57. Slide 57 class EqualsNotEqualTo { public static void main(String args[]) { String str1 = "Hello"; String str2 = new String(str1); System.out.println(str1 + " equals " + str2 + " -> " + str1.equals(str2)); System.out.println(str1 + " == " + str2 + " -> " + (str1 ==str2)); } } Output : Hello equals Hello -> true Hello == Hello -> false String Comparison
  • 58. Slide 58 ● Use the following to make ample modifications to character strings: ● java.lang.StringBuffer ● java.lang.StringBuilder ● Many string object manipulations end up with a many abandoned string objects in the String pool ● String Objects are immutable. StringBuffer sb = new StringBuffer("abc"); sb.append("def"); System.out.println("sb = " + sb); // output is "sb = abcdef" StringBuffer Class
  • 59. Slide 59 ● Added in Java 5. ● Exactly the same API as the StringBuffer class, except: ● It is not thread safe. ● It runs faster than StringBuffer. StringBuilder sb = new StringBuilder("abc"); sb.append("def").reverse().insert(3, "---"); System.out.println( sb ); // output is "fed---cba" StringBuilder Class
  • 61. Slide 61 ● Correspond to primitive data types in Java. ● Represent primitive values as objects. ● Wrapper objects are immutable. Wrapper Classes
  • 62. Slide 62 ● Casting operator converts one variable value to another where two variables correspond to two different data types. variable1 = (variable1) variable2 ● Here, variable2 is typecast to variable1. ● Data type can either be a reference type or a primitive one. Casting for Conversion of Data type
  • 63. Slide 63 ● When one type of data is assigned to another type of variable, automatic type conversion takes place if: ● Both types are compatible. ● Destination type is larger than the source type. ● No explicit casting is needed (widening conversion). int a=5; float b; b=a; ● If there is a possibility of data loss, explicit cast is needed: int i = (int) (5.6/2/7); Casting Between Primitive Types
  • 64. Slide 64 ● One class types involved must be the same class or a subclass of the other class type. ● Assignment to different class types is allowed only if a value of the class type is assigned to a variable of its superclass type. ● Assignment to a variable of the subclass type needs explicit casting: String StrObj = Obj; ● Explicit casting is not needed for the following: String StrObj = new String(“Hello”); Object Obj = StrObj; Casting Between Reference Types
  • 65. Slide 65 ● Two types of reference variable castings: ● Downcasting: Object Obj = new Object ( ); String StrObj = (String) Obj; ● Upcasting: String StrObj = new String(“Hello”); Object Obj = StrObj; Casting Between Reference Types (contd..)