SlideShare a Scribd company logo
1 of 42
Learning Core Java
Abhay Bharti
abhaybharti@gmail.com
@abhaybharti
Sample Code
Agenda (1 / 4 )
1. Introduction to Computers and Java
• Introduction
• Computers: Hardware and Software
• Machine Languages, Assembly Languages
and High- Level Languages
• Introduction to Object Technology
• Operating Systems
• Programming Languages
• Java Development Environment
• Test-Driving Java Application
2. Introduction to Java Applications
• Introduction
• Write Your First Program in Java
• Modifying Your First Java Program
• Displaying Text
• Adding Integers
• Memory Concepts
• Arithmetic
• Decision Making: Equality and Relational
• Conditional Operators
3. Introduction to Classes, Objects, Methods and Strings
• Introduction
• Declaring Class with Method and Instantiating
Object of a Class
• Declaring a Method with Parameter
• Instance Variables, set getter Methods
• Primitive vs. Reference Types
• Initializing Objects with Constructors
• Floating-Point Numbers and double
3. Control Statements: Part 1
• Introduction
• Algorithms
• Control Structures
• if Statement
• if...else Statement
• while Statement
• Compound Assignment Operators
• Increment and Decrement Operators
• Primitive Types
Agenda ( 2 / 4 )
5. Control Statements: Part 2
• Introduction
• Essentials of Counter-Controlled Repetition
• for Repetition Statement
• Examples Using the for Statement
• do...while Repetition Statement
• switch Multiple-Selection Statement
• break and continue Statements
• Logical Operators
• Structured Programming Summary
6. Methods
• Introduction
• Program Modules in Java
• static Methods and static Fields
• Methods with Multiple Parameters
• Method-Call Stack and Activation Records
• Argument Promotion and Casting
• Java API Packages
• Scope of Declarations
• Method Overloading
7. Arrays and ArrayLists
• Introduction
• Arrays
• Declaring and Creating Arrays
• Arrays Examples
• Enhanced for Statement
• Passing Arrays to Methods
• Multidimensional Arrays
• Variable-Length Argument
• Using Command-Line Arguments
• Class Arrays
• Collections and Class ArrayList
8. Classes and Objects: In Detail
• Introduction
• Controlling Access to Members
• Referring to the Current Object’s Members with this
Reference
• Overloaded Constructors
• Default and No-Argument Constructors
• Setter and Getter Methods
• Composition & Enumerations
• Garbage Collection and Method finalize
• static Class Members
• static Import
• final Instance Variables
• Creating & Accessing package
Agenda ( 3 / 4 )
9. Inheritance
• Introduction
• Superclass and Subclass
• protected Members
• Relationship between Superclass and Subclass
• Constructors in Subclasses
• Class Object
10. Polymorphism
• Introduction
• Polymorphism Examples
• Polymorphic Behavior
• Abstract Class and Method
• final Method and Class
• Using Interfaces
11. Exception Handling
• Introduction
• Example: Divide by Zero
• When to Use Exception Handling
• Java Exception Hierarchy
• finally Block
• Obtaining Information from an Exception Object
• Chained Exceptions
• Declaring New Exception Types
• Preconditions and Post-conditions
12. Strings, Characters and Regular Expressions
• Introduction
• Fundamentals of Characters and Strings
• Class String
• String operation
• Class Character
• Tokenizing Strings
• Regular Expressions, Class Pattern and Class
Matcher
13. Files, Streams and Object Serialization
• Introduction
• Files and Streams
• Class File
• Sequential-Access Text Files
• Object Serialization
• Additional java.io Classes
Agenda ( 4 / 4 )
14.Generic Collections
• Introduction
• Collections Overview
• Type-Wrapper Classes for Primitive Types
• Autoboxing and Auto-Unboxing
• Interface Collection and Class Collections
• Lists
• Collections Methods
• Sets
• Maps
• Properties Class
• Synchronized Collections
• Un-modifiable Collections
• Abstract Implementations
15. Generic Classes and Methods
• Introduction
• Motivation for Generic Methods
• Generic Methods: Implementation and Compile-
Time Translation
• Additional Compile-Time Translation Issues:
Methods That Use a Type Parameter as the Return
Type
• Overloading Generic Methods
• Generic Classes
Introduction to Java
o The Java programming language is a high-level language that can be characterized by all of the following
buzzwords:
• Simple
• Object oriented
• Distributed
• Multithreaded
• Dynamic
• Architecture neutral
• Portable
• High performance
• Robust
• Secure
o In Java, source code or program is written in plain text files ending with the .java extension.
o These files are then compiled into .class files by the java compiler.
o A .class file contains bytecodes — the machine language of the Java Virtual Machine (Java VM).
Introduction to Java
o The java launcher tool then runs the program with an instance of the Java Virtual Machine.
o Java VM is available on many different operating systems, the same .class files are capable of running
on multiple hardware platform.
o Java Platform - A platform is the hardware or software environment in which a program runs like
Microsoft Windows, Linux, Solaris OS, and Mac OS. Java is a software-only platform that runs on top of
other hardware-based platforms. It has two components –
• The Java Virtual Machine
• The Java Application Programming Interface (API)
o Install JDK
o Install Eclipse
o Write hello Java program
Introduction to Java
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); }
}
it's the entry point for your application and will subsequently invoke all the other methods required by
your program.
Comments
o/* text */ - The compiler ignores everything from /* to */
o/** documentation */ - This indicates a documentation comment.
o// text The compiler ignores everything from // to the end of the line.
Variables
Java defines following kind of variables –
● Instance Variables (Non-Static Fields) - called as instance variables because their values are unique to
each instance of a class (to each object)
● Class Variables (Static Fields) - A class variable is any field declared with the static modifier; this tells
the compiler that there is exactly one copy of this variable in existence, regardless of how many times
the class has been instantiated.
● Local Variables - a method will often store its temporary state in local variables. local variables are
only visible to the methods in which they are declared; they are not accessible from the rest of the
class.
● Parameters The important thing to remember is that parameters are always classified as "variables"
not "fields".
Naming Convention of variable –
● Variable names are case-sensitive
● A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and
digits, beginning with a letter, the dollar sign "$", or the underscore character "_“
● White space is not permitted
Variables – Primitive Data Type
Java defines following kind of variables –
● byte: The byte data type is an 8-bit. It has a minimum value of -128 and a maximum value of 127
(inclusive).
● short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -
32,768 and a maximum value of 32,767 (inclusive).
● int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -
2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
● long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -
9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
● float: The float data type is a single-precision 32-bit.
● double: The double data type is a double-precision 64-bit.
● boolean: The boolean data type has only two possible values: true and false. Use this data type for
simple flags that track true/false conditions.
● char: The char data type is a single 16-bit Unicode character. It has a minimum value of 'u0000' (or
0) and a maximum value of 'uffff' (or 65,535 inclusive).
Array
Java defines following kind of variables –
● An array is a container object that holds a fixed number of values of a single type. The length of an
array is established when the array is created. After creation, its length is fixed.
● Each item in an array is called an element, and each element is accessed by its numerical index.
● length of the array is determined by the number of values provided between braces and separated by
commas.
● An array of 10 elements
Copying one array value to another array - Java provides arraycopy() method to copy data from one array
into another. Syntax –
arraycopy(Object src_array, int srcPos, Object dest_arrat, int destPos, int length)
● Searching an array for a specific value to get the index at which it is placed (the binarySearch()
method).
● Comparing two arrays to determine if they are equal or not (the equals() method).
● Filling an array to place a specific value at each index (the fill() method).
● Sorting an array into ascending order.
Array
Array Manipulation
● Searching an array for a specific value to get the index at which it is placed (binarySearch() method)
● Comparing two arrays to determine if they are equal or not (the equals() method)
● Filling an array to place a specific value at each index (the fill() method)
● Sorting an array into ascending order
Operator
Simple Assignment Operator :
o = : , int I =10; //This assign the value on the right to variable on the left
Arithmetic :
o + : additive operator (also used for string concatenation)
o - : subtraction operator
o * : multiplication operator
o / : division operator
o % : remainder operator
Conditional Operators
o && : Conditional AND
o || : Conditional OR
Operator
Equality / Relational
o = = : equal to
o ! = : not equal to
o > : greater than
o > = : greater than on equal to
o < : less than
o < = : less than or equal to
Unary Operator
o + : Unary plus operator; indicates positive value (numbers are positive without this, however)
o - : Unary minus operator; negates an expression
o ++ : Increment operator; increments a value by 1
o -- : Decrement operator; decrements a value by 1
o ! : Logical complement operator; inverts the value of a boolean
Control Flow Statement
The statements inside source files are generally executed from top to bottom, in the order that they
appear. Control flow statements, however, break up the flow of execution by employing decision making,
looping, and branching, enabling your program to conditionally execute particular blocks of code.
● If – then statement : It tells the program to execute a certain section of code only if a particular test
evaluates to true. Example –
if (condition) {
}
● If – then - else statement : provides a secondary path of execution when an "if" clause evaluates to
false. Example –
if (condition) {
} else if (condition) {
}else {
}
Control Flow Statement
The switch statement - the switch statement can have a number of possible execution paths. Example -
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
The while and do-while Statements - The while statement continually executes a block of statements while
a particular condition is true. Its syntax can be expressed as:
while (expression) {
statement(s)
}
The difference between do-while and while is that do-while evaluates its expression at the bottom of the
loop instead of the top. Therefore, the statements within the do block are always executed at least once
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
Control Flow Statement
The for statement - It provides a compact way to iterate over a range of values. often called as “for loop”.
Syntax –
for (initialization; termination; increment) {
statement(s)
}
● The initialization expression initializes the loop, it's executed once, as the loop begins.
● When the termination expression evaluates to false, the loop terminates.
● The increment expression is invoked after each iteration through the loop, it may increment or
decrement a value.
Object and Class
● Real-world objects share two characteristics: They all have state and behavior. E.g. Bicycles also have
state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing
pedal cadence, applying brakes).
● An object stores its state in fields (variables in some programming languages) and exposes its
behavior through methods (functions in some programming languages). Methods operate on an
object's internal state and serve as the primary mechanism for object-to-object communication.
Hiding internal state and requiring all interaction to be performed through an object's methods is
known as data encapsulation
● Class - A class is the blueprint from which individual objects are created.
● In object-oriented terms, we say that your bicycle is an instance of the class of objects known as
bicycles.
Class
www.lifegoeasy.blogspot.in
o class declarations includes following components -
• Modifiers such as public, private
• The class name, with the initial letter capitalized by convention
• The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can
only extend (subclass) one parent
• A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
• The class body, surrounded by braces, {}.
o Declaring member variable - Field declarations are composed of three components
• Zero or more modifiers, such as public or private
• The field's type
• The field's name
o Defining a method - A method declaration should have return type, name, a pair of parentheses, (), and
a body between braces, {}.
Class
o Overloading methods - methods within a class can have the same name if they have different
parameter lists
o Constructor - A class contains constructors that are invoked to create objects from the class blueprint.
Constructor declarations look like method declarations—except that they use the name of the class and
have no return type.
Passing information to a Method or a Constructor –
o When you declare a parameter to a method or a constructor, you provide a name for that parameter.
This name is used within the method body to refer to the passed-in argument.
o The name of a parameter must be unique in its scope. It cannot be the same as the name of another
parameter for the same method or constructor, and it cannot be the name of a local variable within the
method or constructor.
o A parameter can have the same name as one of the class's fields
Passing Primitive Data Type Arguments
o Primitive arguments, such as an int or a double, are passed into methods by value. Any changes to the
values of the parameters exist only within the scope of the method. When the method returns, the
parameters are gone and any changes to them are lost.
Class
o When you declare a parameter to a method or a constructor, you provide a name for that parameter.
This name is used within the method body to refer to the passed-in argument.
o The name of a parameter must be unique in its scope. It cannot be the same as the name of another
parameter for the same method or constructor, and it cannot be the name of a local variable within the
method or constructor.
o A parameter can have the same name as one of the class's fields
Passing Primitive Data Type Arguments
o Primitive arguments, such as an int or a double, are passed into methods by value. Any changes to the
values of the parameters exist only within the scope of the method. When the method returns, the
parameters are gone and any changes to them are lost.
Passing Reference Data Type Arguments
o Reference data type parameters, such as objects or array, are also passed into methods by value. This
means that when the method returns, the passed-in reference still references the same object as
before. However, the values of the object's fields can be changed in the method.
Object
A Java program creates many objects, which interact by invoking methods. Through these object
interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or
sending and receiving information over a network. Once an object has completed the work for which it was
created, its resources are recycled for use by other objects.
Creating objects –
Point originOne = new Point(23, 94);
Declaring a variable to Refer an object – This notifies the compiler that you will use name to refer to data
whose type is type
type name;
Instantiating a Class - The new operator instantiates a class by allocating memory for a new object and
returning a reference to that memory. The new operator also invokes the object constructor.
Point originOne = new Point(23, 94);
Initializing an object – constructor is called which initializes the member variable of class
Point originOne = new Point(23, 94);
Object
o Using Objects – Once an object is created, You may use the value of one of its fields, change one of its
fields, or call one of its methods to perform an action.
o Object fields are accessed by their name - objectReference.fieldName
o Calling an Object Method - Object method is invoked using objectreference.methodname() or
objectreference.methodname(argumentlist) and provide argument to the method into parenthesis.
Return a Value from Method - A method returns to the code that invoked it when it
• completes all the statements in the method,
• reaches a return statement, or
• throws an exception
o A method's return type is declared in its method declaration. Within the body of the method, the return
statement is used to return the value.
o A method declared void doesn't return a value. It does not need to contain a return statement
Inheritance
o It allows classes to inherit commonly used state and behavior from other classes.
o each class is allowed to have one direct superclass, and each superclass has the potential for an
unlimited number of subclasses:
o It defines an is-a relationship between a superclass and its subclasses. This means that an object of a
subclass can be used wherever an object of the superclass can be used. Class Inheritance in java
mechanism is used to build new classes from existing classes. The inheritance relationship is transitive:
if class x extends class y, then a class z, which extends class x, will also inherit from class y.
o The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends
keyword, followed by the name of the class to inherit from:
class MountainBike extends Bicycle {
// new fields and methods defining a mountain bike would go here
}
Inheritance
A hierarchy of bicycle classes
o Private members of the superclass are not inherited by the subclass and can only be indirectly
accessed.
o Members that have default accessibility in the superclass are also not inherited by subclasses in
other packages, as these members are only accessible by their simple names in subclasses within the
same package as the superclass.
o Since constructors and initializer blocks are not members of a class, they are not inherited by a
subclass.
o A subclass can extend only one superclass
Inheritance – this & super
o The two keywords, this and super to help you explicitly name the field or method that you want. Using
this and super you have full control on whether to call a method or field present in the same class or to
call from the immediate superclass. This keyword is used as a reference to the current object which is
an instance of the current class. The keyword super also references the current object, but as an
instance of the current class’s super class.
o Note that the this reference cannot be used in a static context, as static code is not executed in the
context of any object.
Interface & Abstract Class
o Abstract classes are used to declare common characteristics of subclasses.
o An abstract class cannot be instantiated.
o It can only be used as a superclass for other classes that extend the abstract class.
o Abstract classes are declared with the abstract keyword.
o It is used to provide a template or design for concrete subclasses down the inheritance tree.
o An abstract class can include methods that contain no implementation. These are called abstract
methods. The abstract method declaration must then end with a semicolon rather than a block.
o Syntax to create abstract class -
abstract class Vehicle {
int numofGears;
String color;
abstract boolean hasDiskBrake();
abstract int getNoofGears();
}
oA big Disadvantage of using abstract classes is not able to use multiple inheritance.
Interface & Abstract Class
o Interface is used to define a generic template and then one or more abstract classes to define partial
implementations of the interface.
o Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields
(which are implicitly public static final). Interface definition begins with a keyword interface.
o An interface can not be instantiated.
o Java does not support multiple inheritance, but it allows you to extend one class and implement many
interfaces.
o If a class that implements an interface does not define all the methods of the interface, then it must be
declared abstract and the method definitions must be provided by the subclass that extends the
abstract class.
o Syntax to create interface -
interface Shape {
public double area();
public double volume();
}
Exception Handling
Exceptions in java is a condition that is caused by a run-time error in the program. Java creates an
exception object and throws. Most common run-time errors are –
o Dividing an integer by zero
o Accessing an element that is out of the bounds of an array
o Attempting to use a negative size of an array
o Converting invalid string to a number
o File not found
Common Java Exceptions
o ArithmeticException – Caused by main errors such as division by zero
o ArrayIndexOutOfBoundException – Caused by bad array indexes
o FileNotFoundException – Caused by an attempt to access a nonexistent file
o IOException - Caused by general I/O failures
o NullPointerException – Caused by referencing a null object
o StringIndexOutOfBoundsException – Caused when a program attempts to access a nonexistent
character position in a string
Exception Class Hierarchy
Exception Handling
checked exception - Exceptional conditions that a well-written application should anticipate and recover
from. Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked
exceptions, except for those indicated by Error.
Error - These are exceptional conditions that are external to the application, and that the application
usually cannot anticipate or recover from. For example, a hardware or system malfunction.
Runtime Exception - These are exceptional conditions that are internal to the application, and that the
application usually cannot anticipate or recover from. These usually indicate programming bugs, such as
logic errors or improper use of an API.
Exception Handling
Exception Handling mechanism –
Collection Framework - Introduction
o A collection represents a group of objects, known as its elements. This framework is provided in the
java.util package.
o Objects can be stored, retrieved, and manipulated as elements of collections.
o Collection is a Java Interface. It can be used in various scenarios like Storing phone numbers, Employee
names database etc. They are basically used to group multiple elements into a single unit.
o Some collections allow duplicate elements while others do not.
o Some collections are ordered and others are not.
o A Collections Framework mainly contains the following 3 parts
o A Collections Framework is defined by a set of interfaces, concrete class implementations for most of
the interfaces and a set of standard utility methods and algorithms. In addition, the framework also
provides several abstract implementations, which are designed to make it easier for you to create new
and different implementations for handling collections of data.
Collection Framework – Interface Details
Core Collection Interfaces
The core interfaces that define common functionality and allow collections to be manipulated independent
of their implementation. The 6 core Interfaces used in the Collection framework are:
1. Collection
2. Set
3. List
4. SortedSet
5. Map
6. SortedMap
7. Iterator (Not a part of the Collections Framework)
Note: Collection and Map are the two top-level interfaces.
Collection Interface
Collection Interface
Collection Detail
ArrayLilst
● ArrayList supports dynamic arrays that can grow as needed.
● Array lists are created with an initial size. When this size is exceeded, the collection is automatically
enlarged. When objects are removed, the array may be shrunk.
● It stores an “ordered” group of elements where duplicates are allowed.
● Accessing elements are faster with ArrayList, because it is index based.
● List arraylistA = new ArrayList();
LinkedList
● It provides a doubly linked-list data structure.
● A LinkedList is used to store an “ordered” group of elements where duplicates are allowed.
● List linkedListA = new LinkedList();
● It is slow access.
Vector
● implements a grow able array of objects. Like an array, it contains components that can be accessed
using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate
adding and removing items after the Vector has been created.
Collection Detail
HashSet
oThe HashSet class implements the Set interface
oit does not guarantee that the order will remain constant over time.
HashMap
oHashMap is a implementation of the Map interface.
oIt stores data in key-value mapping
oThis class makes no guarantees as to the order of the map
oThis implementation provides constant-time performance for the basic operations (get and put)
Access Specifier
o The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class
can control what information or data can be accessible by other classes.
o To take advantage of encapsulation, access should be minimized whenever possible.
o Public - Fields, methods and constructors declared public are visible to any class in the Java program,
whether these classes are in the same package or in another package.
o Private - Fields, methods or constructors declared private are strictly controlled, which means they
cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all
fields private and provide public getter methods for them.
o protected - Fields, methods and constructors declared protected in a superclass can be accessed only
by subclasses in other packages. Classes in the same package can also access protected fields, methods
and constructors as well, even if they are not a subclass of the protected member’s class.
o default - Java provides a default specifier which is used when no access modifier is present. Any class,
field, method or constructor that has no declared access modifier is accessible only by classes in the
same package. The default modifier is not used for fields and methods within an interface.
Multithreading
o Java provides built-in support for multithreaded programming. A multithreaded program contains two
or more parts that can run concurrently. Each part of such a program is called a thread, and each thread
defines a separate path of execution.
o A multithreading is a specialized form of multitasking.
o A process consists of the memory space allocated by the operating system that can contain one or
more threads. A thread cannot exist on its own; it must be a part of a process. A process remains
running until all of the non-daemon threads are done executing.
o Thread can be created in two ways –
1. Create Thread by Implementing Runnable interface – Define a class that implements Runnable
interface. Define run() method with the code to be executed by the thread.
2. Create Thread by Extending Thread – Define a class that extends Thread class and override run()
method.
Multithreading ..
Life Cycle of a Thread -
1. Newborn State: When thread object is created, the thread is born and is said to be in newborn
state. At this state, we can do things –
▪ Schedule it for running using start() method
▪ Kill it using stop() method
2. Runnable State : The thread is ready for execution and is waiting for the availability of the
processor. Yield() method is used to allow a thread to relinquish control to another thread of
equal priority before its turn comes.
3. Running State: it means processor has given its time to the thread for execution. The thread runs
until it relinquishes control on its own or it is preempted by a higher priority thread.
▪ A thread can be suspended using suspended() method and can be revived using resumed
method. This is useful when we want to stop execution of a thread for some time but do not
want to kill it.
▪ A thread is made to go out of queue using sleep(millisecond) method, it will be back in
runnable state as soon as time period is elapsed.
Multithreading …
4. Blocked State: A blocked thread is considered not runnable but not dead and therefore fully
qualified to run again. This happens when a thread is suspended, sleeping or waiting.
5. Dead State : A running thread ends its life when it has completed executing its run() method. It is
natural death. We can kill a thread by sending stop() method.
Thread Priorities
● Every Java thread has a priority that helps the operating system determine the order in which threads
are scheduled.
● Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a
constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
● Threads with higher priority are more important to a program and should be allocated processor time
before lower-priority threads. However, thread priorities cannot guarantee the order in which
threads execute and very much platform dependentant.
Any Questions..

More Related Content

What's hot

L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variablesteach4uin
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput Ahmad Idrees
 
Local variables Instance variables Class/static variables
Local variables Instance variables Class/static variablesLocal variables Instance variables Class/static variables
Local variables Instance variables Class/static variablesSohanur63
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and OperatorsMarwa Ali Eissa
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and VariablesNilesh Dalvi
 
Implementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyImplementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyMartin Odersky
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
C++ training
C++ training C++ training
C++ training PL Sharma
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 

What's hot (19)

L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
#_ varible function
#_ varible function #_ varible function
#_ varible function
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
 
02 data types in java
02 data types in java02 data types in java
02 data types in java
 
Variable
VariableVariable
Variable
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
Local variables Instance variables Class/static variables
Local variables Instance variables Class/static variablesLocal variables Instance variables Class/static variables
Local variables Instance variables Class/static variables
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
PCSTt11 overview of java
PCSTt11 overview of javaPCSTt11 overview of java
PCSTt11 overview of java
 
3. Data types and Variables
3. Data types and Variables3. Data types and Variables
3. Data types and Variables
 
Implementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyImplementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in Dotty
 
From DOT to Dotty
From DOT to DottyFrom DOT to Dotty
From DOT to Dotty
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
C++ training
C++ training C++ training
C++ training
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 
Lecture 1 - Objects and classes
Lecture 1 - Objects and classesLecture 1 - Objects and classes
Lecture 1 - Objects and classes
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 

Similar to Learning core java

Similar to Learning core java (20)

Java ce241
Java ce241Java ce241
Java ce241
 
Java platform
Java platformJava platform
Java platform
 
intro_java (1).pptx
intro_java (1).pptxintro_java (1).pptx
intro_java (1).pptx
 
Java
JavaJava
Java
 
Java
JavaJava
Java
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
ppt_on_java.pptx
ppt_on_java.pptxppt_on_java.pptx
ppt_on_java.pptx
 
Java
JavaJava
Java
 
Module 1.pptx
Module 1.pptxModule 1.pptx
Module 1.pptx
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
Unit 1
Unit 1Unit 1
Unit 1
 
Java
Java Java
Java
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Java Basics
Java BasicsJava Basics
Java Basics
 
core_java.ppt
core_java.pptcore_java.ppt
core_java.ppt
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Java SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).pptJava SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).ppt
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 Certifications
 
Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
 
chapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptxchapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptx
 

Recently uploaded

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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 Pakistandanishmna97
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 

Recently uploaded (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Learning core java

  • 1. Learning Core Java Abhay Bharti abhaybharti@gmail.com @abhaybharti Sample Code
  • 2. Agenda (1 / 4 ) 1. Introduction to Computers and Java • Introduction • Computers: Hardware and Software • Machine Languages, Assembly Languages and High- Level Languages • Introduction to Object Technology • Operating Systems • Programming Languages • Java Development Environment • Test-Driving Java Application 2. Introduction to Java Applications • Introduction • Write Your First Program in Java • Modifying Your First Java Program • Displaying Text • Adding Integers • Memory Concepts • Arithmetic • Decision Making: Equality and Relational • Conditional Operators 3. Introduction to Classes, Objects, Methods and Strings • Introduction • Declaring Class with Method and Instantiating Object of a Class • Declaring a Method with Parameter • Instance Variables, set getter Methods • Primitive vs. Reference Types • Initializing Objects with Constructors • Floating-Point Numbers and double 3. Control Statements: Part 1 • Introduction • Algorithms • Control Structures • if Statement • if...else Statement • while Statement • Compound Assignment Operators • Increment and Decrement Operators • Primitive Types
  • 3. Agenda ( 2 / 4 ) 5. Control Statements: Part 2 • Introduction • Essentials of Counter-Controlled Repetition • for Repetition Statement • Examples Using the for Statement • do...while Repetition Statement • switch Multiple-Selection Statement • break and continue Statements • Logical Operators • Structured Programming Summary 6. Methods • Introduction • Program Modules in Java • static Methods and static Fields • Methods with Multiple Parameters • Method-Call Stack and Activation Records • Argument Promotion and Casting • Java API Packages • Scope of Declarations • Method Overloading 7. Arrays and ArrayLists • Introduction • Arrays • Declaring and Creating Arrays • Arrays Examples • Enhanced for Statement • Passing Arrays to Methods • Multidimensional Arrays • Variable-Length Argument • Using Command-Line Arguments • Class Arrays • Collections and Class ArrayList 8. Classes and Objects: In Detail • Introduction • Controlling Access to Members • Referring to the Current Object’s Members with this Reference • Overloaded Constructors • Default and No-Argument Constructors • Setter and Getter Methods • Composition & Enumerations • Garbage Collection and Method finalize • static Class Members • static Import • final Instance Variables • Creating & Accessing package
  • 4. Agenda ( 3 / 4 ) 9. Inheritance • Introduction • Superclass and Subclass • protected Members • Relationship between Superclass and Subclass • Constructors in Subclasses • Class Object 10. Polymorphism • Introduction • Polymorphism Examples • Polymorphic Behavior • Abstract Class and Method • final Method and Class • Using Interfaces 11. Exception Handling • Introduction • Example: Divide by Zero • When to Use Exception Handling • Java Exception Hierarchy • finally Block • Obtaining Information from an Exception Object • Chained Exceptions • Declaring New Exception Types • Preconditions and Post-conditions 12. Strings, Characters and Regular Expressions • Introduction • Fundamentals of Characters and Strings • Class String • String operation • Class Character • Tokenizing Strings • Regular Expressions, Class Pattern and Class Matcher 13. Files, Streams and Object Serialization • Introduction • Files and Streams • Class File • Sequential-Access Text Files • Object Serialization • Additional java.io Classes
  • 5. Agenda ( 4 / 4 ) 14.Generic Collections • Introduction • Collections Overview • Type-Wrapper Classes for Primitive Types • Autoboxing and Auto-Unboxing • Interface Collection and Class Collections • Lists • Collections Methods • Sets • Maps • Properties Class • Synchronized Collections • Un-modifiable Collections • Abstract Implementations 15. Generic Classes and Methods • Introduction • Motivation for Generic Methods • Generic Methods: Implementation and Compile- Time Translation • Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type • Overloading Generic Methods • Generic Classes
  • 6. Introduction to Java o The Java programming language is a high-level language that can be characterized by all of the following buzzwords: • Simple • Object oriented • Distributed • Multithreaded • Dynamic • Architecture neutral • Portable • High performance • Robust • Secure o In Java, source code or program is written in plain text files ending with the .java extension. o These files are then compiled into .class files by the java compiler. o A .class file contains bytecodes — the machine language of the Java Virtual Machine (Java VM).
  • 7. Introduction to Java o The java launcher tool then runs the program with an instance of the Java Virtual Machine. o Java VM is available on many different operating systems, the same .class files are capable of running on multiple hardware platform. o Java Platform - A platform is the hardware or software environment in which a program runs like Microsoft Windows, Linux, Solaris OS, and Mac OS. Java is a software-only platform that runs on top of other hardware-based platforms. It has two components – • The Java Virtual Machine • The Java Application Programming Interface (API) o Install JDK o Install Eclipse o Write hello Java program
  • 8. Introduction to Java class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); } } it's the entry point for your application and will subsequently invoke all the other methods required by your program. Comments o/* text */ - The compiler ignores everything from /* to */ o/** documentation */ - This indicates a documentation comment. o// text The compiler ignores everything from // to the end of the line.
  • 9. Variables Java defines following kind of variables – ● Instance Variables (Non-Static Fields) - called as instance variables because their values are unique to each instance of a class (to each object) ● Class Variables (Static Fields) - A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. ● Local Variables - a method will often store its temporary state in local variables. local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. ● Parameters The important thing to remember is that parameters are always classified as "variables" not "fields". Naming Convention of variable – ● Variable names are case-sensitive ● A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_“ ● White space is not permitted
  • 10. Variables – Primitive Data Type Java defines following kind of variables – ● byte: The byte data type is an 8-bit. It has a minimum value of -128 and a maximum value of 127 (inclusive). ● short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of - 32,768 and a maximum value of 32,767 (inclusive). ● int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of - 2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). ● long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of - 9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). ● float: The float data type is a single-precision 32-bit. ● double: The double data type is a double-precision 64-bit. ● boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. ● char: The char data type is a single 16-bit Unicode character. It has a minimum value of 'u0000' (or 0) and a maximum value of 'uffff' (or 65,535 inclusive).
  • 11. Array Java defines following kind of variables – ● An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. ● Each item in an array is called an element, and each element is accessed by its numerical index. ● length of the array is determined by the number of values provided between braces and separated by commas. ● An array of 10 elements Copying one array value to another array - Java provides arraycopy() method to copy data from one array into another. Syntax – arraycopy(Object src_array, int srcPos, Object dest_arrat, int destPos, int length) ● Searching an array for a specific value to get the index at which it is placed (the binarySearch() method). ● Comparing two arrays to determine if they are equal or not (the equals() method). ● Filling an array to place a specific value at each index (the fill() method). ● Sorting an array into ascending order.
  • 12. Array Array Manipulation ● Searching an array for a specific value to get the index at which it is placed (binarySearch() method) ● Comparing two arrays to determine if they are equal or not (the equals() method) ● Filling an array to place a specific value at each index (the fill() method) ● Sorting an array into ascending order Operator Simple Assignment Operator : o = : , int I =10; //This assign the value on the right to variable on the left Arithmetic : o + : additive operator (also used for string concatenation) o - : subtraction operator o * : multiplication operator o / : division operator o % : remainder operator Conditional Operators o && : Conditional AND o || : Conditional OR
  • 13. Operator Equality / Relational o = = : equal to o ! = : not equal to o > : greater than o > = : greater than on equal to o < : less than o < = : less than or equal to Unary Operator o + : Unary plus operator; indicates positive value (numbers are positive without this, however) o - : Unary minus operator; negates an expression o ++ : Increment operator; increments a value by 1 o -- : Decrement operator; decrements a value by 1 o ! : Logical complement operator; inverts the value of a boolean
  • 14. Control Flow Statement The statements inside source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. ● If – then statement : It tells the program to execute a certain section of code only if a particular test evaluates to true. Example – if (condition) { } ● If – then - else statement : provides a secondary path of execution when an "if" clause evaluates to false. Example – if (condition) { } else if (condition) { }else { }
  • 15. Control Flow Statement The switch statement - the switch statement can have a number of possible execution paths. Example - int month = 8; String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break; The while and do-while Statements - The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as: while (expression) { statement(s) } The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once do { System.out.println("Count is: " + count); count++; } while (count < 11);
  • 16. Control Flow Statement The for statement - It provides a compact way to iterate over a range of values. often called as “for loop”. Syntax – for (initialization; termination; increment) { statement(s) } ● The initialization expression initializes the loop, it's executed once, as the loop begins. ● When the termination expression evaluates to false, the loop terminates. ● The increment expression is invoked after each iteration through the loop, it may increment or decrement a value.
  • 17. Object and Class ● Real-world objects share two characteristics: They all have state and behavior. E.g. Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). ● An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation ● Class - A class is the blueprint from which individual objects are created. ● In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.
  • 18. Class www.lifegoeasy.blogspot.in o class declarations includes following components - • Modifiers such as public, private • The class name, with the initial letter capitalized by convention • The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent • A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface. • The class body, surrounded by braces, {}. o Declaring member variable - Field declarations are composed of three components • Zero or more modifiers, such as public or private • The field's type • The field's name o Defining a method - A method declaration should have return type, name, a pair of parentheses, (), and a body between braces, {}.
  • 19. Class o Overloading methods - methods within a class can have the same name if they have different parameter lists o Constructor - A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. Passing information to a Method or a Constructor – o When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument. o The name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor. o A parameter can have the same name as one of the class's fields Passing Primitive Data Type Arguments o Primitive arguments, such as an int or a double, are passed into methods by value. Any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost.
  • 20. Class o When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument. o The name of a parameter must be unique in its scope. It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor. o A parameter can have the same name as one of the class's fields Passing Primitive Data Type Arguments o Primitive arguments, such as an int or a double, are passed into methods by value. Any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost. Passing Reference Data Type Arguments o Reference data type parameters, such as objects or array, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method.
  • 21. Object A Java program creates many objects, which interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects. Creating objects – Point originOne = new Point(23, 94); Declaring a variable to Refer an object – This notifies the compiler that you will use name to refer to data whose type is type type name; Instantiating a Class - The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor. Point originOne = new Point(23, 94); Initializing an object – constructor is called which initializes the member variable of class Point originOne = new Point(23, 94);
  • 22. Object o Using Objects – Once an object is created, You may use the value of one of its fields, change one of its fields, or call one of its methods to perform an action. o Object fields are accessed by their name - objectReference.fieldName o Calling an Object Method - Object method is invoked using objectreference.methodname() or objectreference.methodname(argumentlist) and provide argument to the method into parenthesis. Return a Value from Method - A method returns to the code that invoked it when it • completes all the statements in the method, • reaches a return statement, or • throws an exception o A method's return type is declared in its method declaration. Within the body of the method, the return statement is used to return the value. o A method declared void doesn't return a value. It does not need to contain a return statement
  • 23. Inheritance o It allows classes to inherit commonly used state and behavior from other classes. o each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses: o It defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y. o The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class MountainBike extends Bicycle { // new fields and methods defining a mountain bike would go here }
  • 24. Inheritance A hierarchy of bicycle classes o Private members of the superclass are not inherited by the subclass and can only be indirectly accessed. o Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass. o Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass. o A subclass can extend only one superclass
  • 25. Inheritance – this & super o The two keywords, this and super to help you explicitly name the field or method that you want. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass. This keyword is used as a reference to the current object which is an instance of the current class. The keyword super also references the current object, but as an instance of the current class’s super class. o Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.
  • 26. Interface & Abstract Class o Abstract classes are used to declare common characteristics of subclasses. o An abstract class cannot be instantiated. o It can only be used as a superclass for other classes that extend the abstract class. o Abstract classes are declared with the abstract keyword. o It is used to provide a template or design for concrete subclasses down the inheritance tree. o An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declaration must then end with a semicolon rather than a block. o Syntax to create abstract class - abstract class Vehicle { int numofGears; String color; abstract boolean hasDiskBrake(); abstract int getNoofGears(); } oA big Disadvantage of using abstract classes is not able to use multiple inheritance.
  • 27. Interface & Abstract Class o Interface is used to define a generic template and then one or more abstract classes to define partial implementations of the interface. o Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly public static final). Interface definition begins with a keyword interface. o An interface can not be instantiated. o Java does not support multiple inheritance, but it allows you to extend one class and implement many interfaces. o If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. o Syntax to create interface - interface Shape { public double area(); public double volume(); }
  • 28. Exception Handling Exceptions in java is a condition that is caused by a run-time error in the program. Java creates an exception object and throws. Most common run-time errors are – o Dividing an integer by zero o Accessing an element that is out of the bounds of an array o Attempting to use a negative size of an array o Converting invalid string to a number o File not found Common Java Exceptions o ArithmeticException – Caused by main errors such as division by zero o ArrayIndexOutOfBoundException – Caused by bad array indexes o FileNotFoundException – Caused by an attempt to access a nonexistent file o IOException - Caused by general I/O failures o NullPointerException – Caused by referencing a null object o StringIndexOutOfBoundsException – Caused when a program attempts to access a nonexistent character position in a string
  • 30. Exception Handling checked exception - Exceptional conditions that a well-written application should anticipate and recover from. Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error. Error - These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, a hardware or system malfunction. Runtime Exception - These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API.
  • 32. Collection Framework - Introduction o A collection represents a group of objects, known as its elements. This framework is provided in the java.util package. o Objects can be stored, retrieved, and manipulated as elements of collections. o Collection is a Java Interface. It can be used in various scenarios like Storing phone numbers, Employee names database etc. They are basically used to group multiple elements into a single unit. o Some collections allow duplicate elements while others do not. o Some collections are ordered and others are not. o A Collections Framework mainly contains the following 3 parts o A Collections Framework is defined by a set of interfaces, concrete class implementations for most of the interfaces and a set of standard utility methods and algorithms. In addition, the framework also provides several abstract implementations, which are designed to make it easier for you to create new and different implementations for handling collections of data.
  • 33. Collection Framework – Interface Details Core Collection Interfaces The core interfaces that define common functionality and allow collections to be manipulated independent of their implementation. The 6 core Interfaces used in the Collection framework are: 1. Collection 2. Set 3. List 4. SortedSet 5. Map 6. SortedMap 7. Iterator (Not a part of the Collections Framework) Note: Collection and Map are the two top-level interfaces.
  • 36. Collection Detail ArrayLilst ● ArrayList supports dynamic arrays that can grow as needed. ● Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk. ● It stores an “ordered” group of elements where duplicates are allowed. ● Accessing elements are faster with ArrayList, because it is index based. ● List arraylistA = new ArrayList(); LinkedList ● It provides a doubly linked-list data structure. ● A LinkedList is used to store an “ordered” group of elements where duplicates are allowed. ● List linkedListA = new LinkedList(); ● It is slow access. Vector ● implements a grow able array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
  • 37. Collection Detail HashSet oThe HashSet class implements the Set interface oit does not guarantee that the order will remain constant over time. HashMap oHashMap is a implementation of the Map interface. oIt stores data in key-value mapping oThis class makes no guarantees as to the order of the map oThis implementation provides constant-time performance for the basic operations (get and put)
  • 38. Access Specifier o The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. o To take advantage of encapsulation, access should be minimized whenever possible. o Public - Fields, methods and constructors declared public are visible to any class in the Java program, whether these classes are in the same package or in another package. o Private - Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them. o protected - Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class. o default - Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.
  • 39. Multithreading o Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. o A multithreading is a specialized form of multitasking. o A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing. o Thread can be created in two ways – 1. Create Thread by Implementing Runnable interface – Define a class that implements Runnable interface. Define run() method with the code to be executed by the thread. 2. Create Thread by Extending Thread – Define a class that extends Thread class and override run() method.
  • 40. Multithreading .. Life Cycle of a Thread - 1. Newborn State: When thread object is created, the thread is born and is said to be in newborn state. At this state, we can do things – ▪ Schedule it for running using start() method ▪ Kill it using stop() method 2. Runnable State : The thread is ready for execution and is waiting for the availability of the processor. Yield() method is used to allow a thread to relinquish control to another thread of equal priority before its turn comes. 3. Running State: it means processor has given its time to the thread for execution. The thread runs until it relinquishes control on its own or it is preempted by a higher priority thread. ▪ A thread can be suspended using suspended() method and can be revived using resumed method. This is useful when we want to stop execution of a thread for some time but do not want to kill it. ▪ A thread is made to go out of queue using sleep(millisecond) method, it will be back in runnable state as soon as time period is elapsed.
  • 41. Multithreading … 4. Blocked State: A blocked thread is considered not runnable but not dead and therefore fully qualified to run again. This happens when a thread is suspended, sleeping or waiting. 5. Dead State : A running thread ends its life when it has completed executing its run() method. It is natural death. We can kill a thread by sending stop() method. Thread Priorities ● Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. ● Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5). ● Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependentant.