SlideShare a Scribd company logo
Java Class 4
“Code is like humor. When you have to explain it, it’s
bad.”
•Statics in java
•Constructors
•Exceptions in Java
•String in java
Java Values 2
What is Static Keyword ?
The static keyword in Java is used for
memory management mainly. We can apply
static keyword with variables, methods,
blocks and nested classes. The static
keyword belongs to the class than an
instance of the class.
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class
Java Values 3
Static Variable
Fields that have the static modifier in their
declaration are called static fields or class
variables.
They are associated with the class, rather
than with any object.
Every instance of the class shares a class
variable, which is in one fixed location in
memory.
Any object can change the value of a class
variable, but class variables can also be
manipulated without creating an instance of
the class.
Syntax : <class-name>.<variable-name>
Static methods
The Java programming language supports
static methods as well as static variables.
main method is static , since it must be
accessible for an application to run , before any
instantiation takes place.
Static methods, which have the static modifier
in their declarations, should be invoked with the
class name, without the need for creating an
instance of the class, as in
ex. ClassName.methodName(args)
Java Values 4
Static methods
A common use for static methods is to
access static fields.
For example, we could add a static method
to the Bicycle class to access the static field
numberOfBicycles :
Java Values 5
public static int getNumberOfBicycles() {
return numberOfBicycles;
}
Static methods
Not all combinations of instance and class
variables and methods are allowed:
• Instance methods can access instance
variables and instance methods directly.
• Instance methods can access class variables
and class methods directly.
• Class methods can access class variables and
class methods directly.
• Class methods cannot access instance
variables or instance methods directly—they
must use an object reference. Also, class
methods cannot use the this or super keywords,
as there is no instance to refer to.
Java Values 6
Constants
Constant fields are often declared as static.
For example NUM_OF_WHEELS which is a
characteristic of any Bicycle, and not of a
certain instance.
If there’s a sense to expose a constant field
to the outside world, it is common to declare
the field as public, rather than through a
getter.
Java Values 7
Singleton pattern
Restricting the instantiation of a certain class
to exactly one object.
This is useful when exactly one object is
needed to coordinate actions across the
system.
A singleton object is accessible globally
using a static method.
Java Values 8
Singleton
Java Values 9
public class Controller {
private static Controller instance = null;
private Controller () { ... }
public static Controller getInstance() {
if (instance == null) {
instance = new Controller ();
}
return instance;
}
...
}
* Not thread-safe
Notice the private
constructor
A static block
The static block, is a block of statement
inside a Java class that will be executed
when a class is first loaded in to the JVM.
A static block helps to initialize the static
data members, just like constructors help to
initialize instance members.
 public class Controller {
private static Controller instance;
static {
instance = new Controller ();
}
private Controller () { }
public static Controller getInstance() {
return instance;
}
 }
Java Values 10
Example of static
EX: 1
class A2{
static{
System.out.println("static block is
invoked");
}
public static void main(String args
[]){
System.out.println("Hello main");
}
}
output : ?
Java Values 11
EX: 2
class TestOuter1{
static int data=30;
static class Inner{
void msg(){
System.out.println("data is : "+data);
}
}
public static void main(String args[]){
TestOuter1.Inobj=new TestOuter1.Inner();
obj.msg();
}
}
Java static nested class
A static class i.e. created inside a class is called
static nested class in java. It cannot access non-
static data members and methods. It can be
accessed by outer class name.
It can access static data members of outer class
including private.
Static nested class cannot access non-static
(instance) data member or method.
For Example Refer previous slide EX:2 output?
Java Values 12
What is Constructors ?
In Java, a constructor is a block of codes
similar to the method. It is called when an
instance of the class is created. At the time
of calling constructor, memory for the object
is allocated in the memory.
It is a special type of method which is used
to initialize the object.
Every time an object is created using the
new() keyword, at least one constructor is
called.
Java Values 13
Rules for creating constructor
There are two rules defined for the constructor.
Constructor name must be the same as its class
name
A Constructor must have no explicit return type.
A Java constructor cannot be abstract, static, final,
and synchronized
class Bike1{
Bike1(){ //creating a default constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1(); //calling a default constructor
}
}
Java Values 14
Type of Constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
If there is no constructor in a class, compiler automatically creates a
default constructor.
Java Values 15
class Student4{
int id; // default value 0
String name; //default value null
// if we not pass the int I and string n value it will give default value
Student4(int i,String n){ //creating a parameterized constructor
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Java Values 16
Output:?
Constructor Chaining
Calling a constructor from the another
constructor of same class is known as
Constructor chaining..
Java Values 17
This and Super constructors
this() and super() are used to call
constructors explicitly.
1. Using this() you can call the current class’s constructor
2. Using super() you can call the constructor of the super
class.
Java Values 18
class A
{
public int x, y;
public A(int x, int y) {
this.x = x; this.y = y;
}
}
class B extends A {
public int x, y;
public B() {
this(0, 0);
}
public B(int x, int y) {
super(x + 1, y + 1); // calls parent
class constructor
this.x = x;
this.y = y;
}
Java Values 19
public void print() {
System.out.println("Base class : {" + x + ", "
+ y + "}");
System.out.println("Super class : {" +
super.x + ", " + super.y + "}");
}
}
class Point
{
public static void main(String[] args) {
B obj = new B();
obj.print();
obj = new B(1, 2);
obj.print();
}
}
? Answer
Constructors for Enumerated Data Types
enum Car {
lamborghini(900),tata(2),audi(50),fiat(15),honda(12); //Enum datatype
private int price;
Car(int p) {
price = p; }
int getPrice() {
return price;
}
}
public class Main {
public static void main(String args[]){
System.out.println("All car prices:");
for (Car c : Car.values())
System.out.println( c + " costs " + c.getPrice() + " thousand dollars.");
}
} Java Values 20
Java Values 21
Exception ??
Java Values 22Exception is an abnormal condition.
What ? Why ? How?
In Java, an exception is an event that disrupts the
normal flow of the program. It is an object which is
thrown at runtime.
Exception Handling is a mechanism to handle
runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException,
etc.
The core advantage of exception handling is to
maintain the normal flow of the application. An
exception normally disrupts the normal flow of the
application that is why we use exception handling.
Java Values 23
API hierarchy for Exceptions
Java Values 24
Parent class
Types of Exceptions
Java Values 25
Java Values.com
Keywords in Exception API
Java Values 26
Java Values 27
Catching Exceptions
 The try-catch Statements
● Syntax:
try {
<code to be monitored for exceptions>
} catch (<ExceptionType1> <ObjName>) {
<handler if ExceptionType1 occurs>
}
...
} catch (<ExceptionTypeN> <ObjName>) {
<handler if ExceptionTypeN occurs>
 } finally {
 <code to be executed before the try block ends>
 }
Java Values 28
Throwing Exceptions
The throw Keyword
● Java allows you to throw exceptions (generate exceptions)
ex. throw <exception object>;
● An exception you throw is an object
– You have to create an exception object in the same way you create
any other object
● Example:
throw new ArithmeticException(“testing...”);
class TestHateString {
public static void main(String args[]) {
String input = "invalid input";
try {
if (input.equals("invalid input")) {
throw new HateStringExp();
}
System.out.println("Accept string.");
Java Values 29
} catch (HateStringExp e) {
System.out.println("Hate string!”);
}
}
}
Example 2
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}
Java Values 30
Output:?
String in Java
Java Values 31
Java Values
Strings
String is a sequence of characters placed in
double quote(“ ”). //(“JAVA”)
Strings are constant , their values cannot be
changed in the same memory after they are
created.
There are two ways to create String
object:
1)By string literal.
2)By new keyword.
Java Values 32
String Creation
By string literal:
For Example: String s1=“welcome";
String s2=“welcome”;
//no new object will be created
Java Values 33
By new keyword:-
For Example:
String s=new String(“Sachin");
String s=newString(“SachinTendulkar");
//create two objects and one reference variable
Java Values 34
Immutability
In java, string objects are immutable.
Immutable simply means unmodifiable or
unchangeable.
Once string object is created its data or state
can't be changed but a new string object is
created.
Advantage of immutability is Use of less
memory
Disadvantages of Immutability: Less efficient —
you need to create a new string and throw away
the old one even for small changes
Java Values 35
String word1 = "Java";
String word2 = word1;
Word1
Java
word2
OK
Java Values 36
String word1 = “Java";
String word2 =new String(word1);
Word1 Java
Word2 Java
Less efficient: wastes memory
String Methods
substring(int begin):
Returns substring from begin index to end of the String.
Example: String s=“nacre”;
System.out.println(s.substring(2));//cre
equals():
To perform content comparision where case is important.
Example: String s=“java”;
System.out.println(s.equals(“java”));//true
concat(): Adding two strings we use this method
Example: String s=“nacre”;
s= s.concat(“software”);
System.out.println(s);// nacresoftware
Java Values 37
length() , charAt()
int length(); Returns the number of characters in the string
char charAt(i); Returns the char at position i.
Character positions in strings are numbered starting from
0 – just like arrays.
Returns:
“Problem".length(); 7
“Window”. charAt (2); ’n'
Java Values 38
StringBuffer, StringBuilder
StringTokenizer
Java Values 39
Java values
All These classes are final and subclass of Serializable.
Limitation of String in Java ?
What is mutable string?
A string that can be modified or changed is known
as mutable string. StringBuffer and StringBuilder
classes are used for creating mutable string.
Differences between String and StringBuffer in java?
Main difference between String and StringBuffer is
String is immutable while StringBuffer is mutable
Java Values 40
StringBuffer
StringBuffer is a synchronized and allows us to
mutate the string.
StringBuffer has many utility methods to manipulate
the string.
This is more useful when using in multithreaded
environment.
Always modified in same memory location.
Methods:
1. Append 2. Insert 3.Delete 4.Reverse
5.Replacing Character at given index
Java Values 41
StringBuilder
StringBuilder is the same as the StringBuffer class.
The StringBuilder class is not synchronized and
hence in a single threaded environment, the
overhead is less than using a StringBuffer.
public class Test
{
public static void main(String[] args)
{
String str = “Java";
StringBuffer sbr = new StringBuffer(str);
sbr.reverse();
System.out.println(sbr);
// conversion from String object to StringBuilder
StringBuilder sbl = new StringBuilder(str);
sbl.append(“Values");
System.out.println(sbl);
}
}
Java Values 42
Output?
StringTokenizer
A token is a portion of a string that is separated from another
portion of that string by one or more chosen characters (called
delimiters).
The StringTokenizer class contained in the java.util package
can be used to break a string into separate tokens. This is
particularly useful in those situations in which we want to read
and process one token at a time; the BufferedReader class
does not have a method to read one token at a time.
Java Values 43
Java Values 44
Java Values
“Hello world welcome to Java Values”
String Tokenizer
Token
Hello
world
welcome
to
Java
Values
Java Values 45
Java Values 46
 Statics
variable, Method, block, nested class
 Constructors
default ,no-arg, parameterize
 Exceptions in Java
Checked –unchecked, exception, error , try-catch-finally-throw-throws,
customize exception
 String
String –Stringbuffer-StringBuilder-String Tokenizer
Q & A
???
Java Values 47
For engineering project or live project internship please contact us Mindlabz Software Technology

More Related Content

What's hot (17)

PDF
Core Java Introduction | Basics
Hùng Nguyễn Huy
 
PPT
Java Tutorial
Singsys Pte Ltd
 
PDF
Object Oriented Programming in PHP
Lorna Mitchell
 
DOCX
Core java notes with examples
bindur87
 
PPT
Java static keyword
Lovely Professional University
 
PPT
Java
Prabhat gangwar
 
PDF
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
PPTX
Classes and objects
rajveer_Pannu
 
PPTX
Introduction to OOP(in java) BY Govind Singh
prabhat engineering college
 
PPT
Object and Classes in Java
backdoor
 
PPTX
Static keyword ppt
Vinod Kumar
 
PPT
Oops in Java
malathip12
 
PPS
Introduction to class in java
kamal kotecha
 
PPT
Java tutorials
saryu2011
 
PPTX
Basics of Java
Sherihan Anver
 
PPTX
03 object-classes-pbl-4-slots
mha4
 
Core Java Introduction | Basics
Hùng Nguyễn Huy
 
Java Tutorial
Singsys Pte Ltd
 
Object Oriented Programming in PHP
Lorna Mitchell
 
Core java notes with examples
bindur87
 
Java static keyword
Lovely Professional University
 
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
Classes and objects
rajveer_Pannu
 
Introduction to OOP(in java) BY Govind Singh
prabhat engineering college
 
Object and Classes in Java
backdoor
 
Static keyword ppt
Vinod Kumar
 
Oops in Java
malathip12
 
Introduction to class in java
kamal kotecha
 
Java tutorials
saryu2011
 
Basics of Java
Sherihan Anver
 
03 object-classes-pbl-4-slots
mha4
 

Similar to Statics in java | Constructors | Exceptions in Java | String in java| class 3 (20)

PPTX
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
PPTX
Module 1.pptx
YakaviBalakrishnan
 
PPTX
UNIT 3- Java- Inheritance, Multithreading.pptx
shilpar780389
 
PDF
Unit 2 Part 1 Constructors.pdf
Arpana Awasthi
 
PPTX
Java Programs
vvpadhu
 
PDF
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
PPTX
Java Tokens in java program . pptx
CmDept
 
PDF
Java basic concept
University of Potsdam
 
ODP
Synapseindia reviews.odp.
Tarunsingh198
 
PPTX
Class and Object.pptx from nit patna ece department
om2348023vats
 
PPT
JavaTutorials.ppt
Khizar40
 
PPTX
Java For Automation
Abhijeet Dubey
 
PPTX
UNIT - IIInew.pptx
akila m
 
PDF
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
PPTX
Core Java Tutorials by Mahika Tutorials
Mahika Tutorials
 
PPTX
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Soumen Santra
 
PPTX
Java introduction
The icfai university jaipur
 
PPTX
Java static keyword
Ahmed Shawky El-faky
 
PDF
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
bca23189c
 
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
Module 1.pptx
YakaviBalakrishnan
 
UNIT 3- Java- Inheritance, Multithreading.pptx
shilpar780389
 
Unit 2 Part 1 Constructors.pdf
Arpana Awasthi
 
Java Programs
vvpadhu
 
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Java Tokens in java program . pptx
CmDept
 
Java basic concept
University of Potsdam
 
Synapseindia reviews.odp.
Tarunsingh198
 
Class and Object.pptx from nit patna ece department
om2348023vats
 
JavaTutorials.ppt
Khizar40
 
Java For Automation
Abhijeet Dubey
 
UNIT - IIInew.pptx
akila m
 
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
Core Java Tutorials by Mahika Tutorials
Mahika Tutorials
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Soumen Santra
 
Java introduction
The icfai university jaipur
 
Java static keyword
Ahmed Shawky El-faky
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
bca23189c
 
Ad

More from Sagar Verma (6)

PPT
Java introduction
Sagar Verma
 
PPT
Hibernate introduction
Sagar Verma
 
PPT
Springboot introduction
Sagar Verma
 
PDF
2015-16 software project list
Sagar Verma
 
DOC
Ns2 new project list
Sagar Verma
 
PPT
Privacy preserving dm_ppt
Sagar Verma
 
Java introduction
Sagar Verma
 
Hibernate introduction
Sagar Verma
 
Springboot introduction
Sagar Verma
 
2015-16 software project list
Sagar Verma
 
Ns2 new project list
Sagar Verma
 
Privacy preserving dm_ppt
Sagar Verma
 
Ad

Recently uploaded (20)

PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PPT
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PPTX
Big Data and Data Science hype .pptx
SUNEEL37
 
PPTX
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
Knowledge Representation : Semantic Networks
Amity University, Patna
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PDF
smart lot access control system with eye
rasabzahra
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
Carmon_Remote Sensing GIS by Mahesh kumar
DhananjayM6
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
Big Data and Data Science hype .pptx
SUNEEL37
 
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
Knowledge Representation : Semantic Networks
Amity University, Patna
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
smart lot access control system with eye
rasabzahra
 
Design Thinking basics for Engineers.pdf
CMR University
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 

Statics in java | Constructors | Exceptions in Java | String in java| class 3

  • 1. Java Class 4 “Code is like humor. When you have to explain it, it’s bad.” •Statics in java •Constructors •Exceptions in Java •String in java
  • 2. Java Values 2 What is Static Keyword ? The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class. Variable (also known as a class variable) Method (also known as a class method) Block Nested class
  • 3. Java Values 3 Static Variable Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class. Syntax : <class-name>.<variable-name>
  • 4. Static methods The Java programming language supports static methods as well as static variables. main method is static , since it must be accessible for an application to run , before any instantiation takes place. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in ex. ClassName.methodName(args) Java Values 4
  • 5. Static methods A common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the static field numberOfBicycles : Java Values 5 public static int getNumberOfBicycles() { return numberOfBicycles; }
  • 6. Static methods Not all combinations of instance and class variables and methods are allowed: • Instance methods can access instance variables and instance methods directly. • Instance methods can access class variables and class methods directly. • Class methods can access class variables and class methods directly. • Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this or super keywords, as there is no instance to refer to. Java Values 6
  • 7. Constants Constant fields are often declared as static. For example NUM_OF_WHEELS which is a characteristic of any Bicycle, and not of a certain instance. If there’s a sense to expose a constant field to the outside world, it is common to declare the field as public, rather than through a getter. Java Values 7
  • 8. Singleton pattern Restricting the instantiation of a certain class to exactly one object. This is useful when exactly one object is needed to coordinate actions across the system. A singleton object is accessible globally using a static method. Java Values 8
  • 9. Singleton Java Values 9 public class Controller { private static Controller instance = null; private Controller () { ... } public static Controller getInstance() { if (instance == null) { instance = new Controller (); } return instance; } ... } * Not thread-safe Notice the private constructor
  • 10. A static block The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM. A static block helps to initialize the static data members, just like constructors help to initialize instance members.  public class Controller { private static Controller instance; static { instance = new Controller (); } private Controller () { } public static Controller getInstance() { return instance; }  } Java Values 10
  • 11. Example of static EX: 1 class A2{ static{ System.out.println("static block is invoked"); } public static void main(String args []){ System.out.println("Hello main"); } } output : ? Java Values 11 EX: 2 class TestOuter1{ static int data=30; static class Inner{ void msg(){ System.out.println("data is : "+data); } } public static void main(String args[]){ TestOuter1.Inobj=new TestOuter1.Inner(); obj.msg(); } }
  • 12. Java static nested class A static class i.e. created inside a class is called static nested class in java. It cannot access non- static data members and methods. It can be accessed by outer class name. It can access static data members of outer class including private. Static nested class cannot access non-static (instance) data member or method. For Example Refer previous slide EX:2 output? Java Values 12
  • 13. What is Constructors ? In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called. Java Values 13
  • 14. Rules for creating constructor There are two rules defined for the constructor. Constructor name must be the same as its class name A Constructor must have no explicit return type. A Java constructor cannot be abstract, static, final, and synchronized class Bike1{ Bike1(){ //creating a default constructor System.out.println("Bike is created"); } public static void main(String args[]){ Bike1 b=new Bike1(); //calling a default constructor } } Java Values 14
  • 15. Type of Constructors There are two types of constructors in Java: 1. Default constructor (no-arg constructor) 2. Parameterized constructor If there is no constructor in a class, compiler automatically creates a default constructor. Java Values 15
  • 16. class Student4{ int id; // default value 0 String name; //default value null // if we not pass the int I and string n value it will give default value Student4(int i,String n){ //creating a parameterized constructor id = i; name = n; } //method to display the values void display(){System.out.println(id+" "+name);} public static void main(String args[]){ //creating objects and passing values Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); //calling method to display the values of object s1.display(); s2.display(); } } Java Values 16 Output:?
  • 17. Constructor Chaining Calling a constructor from the another constructor of same class is known as Constructor chaining.. Java Values 17
  • 18. This and Super constructors this() and super() are used to call constructors explicitly. 1. Using this() you can call the current class’s constructor 2. Using super() you can call the constructor of the super class. Java Values 18
  • 19. class A { public int x, y; public A(int x, int y) { this.x = x; this.y = y; } } class B extends A { public int x, y; public B() { this(0, 0); } public B(int x, int y) { super(x + 1, y + 1); // calls parent class constructor this.x = x; this.y = y; } Java Values 19 public void print() { System.out.println("Base class : {" + x + ", " + y + "}"); System.out.println("Super class : {" + super.x + ", " + super.y + "}"); } } class Point { public static void main(String[] args) { B obj = new B(); obj.print(); obj = new B(1, 2); obj.print(); } } ? Answer
  • 20. Constructors for Enumerated Data Types enum Car { lamborghini(900),tata(2),audi(50),fiat(15),honda(12); //Enum datatype private int price; Car(int p) { price = p; } int getPrice() { return price; } } public class Main { public static void main(String args[]){ System.out.println("All car prices:"); for (Car c : Car.values()) System.out.println( c + " costs " + c.getPrice() + " thousand dollars."); } } Java Values 20
  • 22. Exception ?? Java Values 22Exception is an abnormal condition.
  • 23. What ? Why ? How? In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc. The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application that is why we use exception handling. Java Values 23
  • 24. API hierarchy for Exceptions Java Values 24 Parent class
  • 25. Types of Exceptions Java Values 25 Java Values.com
  • 26. Keywords in Exception API Java Values 26
  • 28. Catching Exceptions  The try-catch Statements ● Syntax: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs>  } finally {  <code to be executed before the try block ends>  } Java Values 28
  • 29. Throwing Exceptions The throw Keyword ● Java allows you to throw exceptions (generate exceptions) ex. throw <exception object>; ● An exception you throw is an object – You have to create an exception object in the same way you create any other object ● Example: throw new ArithmeticException(“testing...”); class TestHateString { public static void main(String args[]) { String input = "invalid input"; try { if (input.equals("invalid input")) { throw new HateStringExp(); } System.out.println("Accept string."); Java Values 29 } catch (HateStringExp e) { System.out.println("Hate string!”); } } }
  • 30. Example 2 class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } } class TestCustomException1{ static void validate(int age)throws InvalidAgeException{ if(age<18) throw new InvalidAgeException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ try{ validate(13); }catch(Exception m){System.out.println("Exception occured: "+m);} System.out.println("rest of the code..."); } } Java Values 30 Output:?
  • 31. String in Java Java Values 31 Java Values
  • 32. Strings String is a sequence of characters placed in double quote(“ ”). //(“JAVA”) Strings are constant , their values cannot be changed in the same memory after they are created. There are two ways to create String object: 1)By string literal. 2)By new keyword. Java Values 32
  • 33. String Creation By string literal: For Example: String s1=“welcome"; String s2=“welcome”; //no new object will be created Java Values 33
  • 34. By new keyword:- For Example: String s=new String(“Sachin"); String s=newString(“SachinTendulkar"); //create two objects and one reference variable Java Values 34
  • 35. Immutability In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once string object is created its data or state can't be changed but a new string object is created. Advantage of immutability is Use of less memory Disadvantages of Immutability: Less efficient — you need to create a new string and throw away the old one even for small changes Java Values 35
  • 36. String word1 = "Java"; String word2 = word1; Word1 Java word2 OK Java Values 36 String word1 = “Java"; String word2 =new String(word1); Word1 Java Word2 Java Less efficient: wastes memory
  • 37. String Methods substring(int begin): Returns substring from begin index to end of the String. Example: String s=“nacre”; System.out.println(s.substring(2));//cre equals(): To perform content comparision where case is important. Example: String s=“java”; System.out.println(s.equals(“java”));//true concat(): Adding two strings we use this method Example: String s=“nacre”; s= s.concat(“software”); System.out.println(s);// nacresoftware Java Values 37
  • 38. length() , charAt() int length(); Returns the number of characters in the string char charAt(i); Returns the char at position i. Character positions in strings are numbered starting from 0 – just like arrays. Returns: “Problem".length(); 7 “Window”. charAt (2); ’n' Java Values 38
  • 39. StringBuffer, StringBuilder StringTokenizer Java Values 39 Java values All These classes are final and subclass of Serializable.
  • 40. Limitation of String in Java ? What is mutable string? A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder classes are used for creating mutable string. Differences between String and StringBuffer in java? Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable Java Values 40
  • 41. StringBuffer StringBuffer is a synchronized and allows us to mutate the string. StringBuffer has many utility methods to manipulate the string. This is more useful when using in multithreaded environment. Always modified in same memory location. Methods: 1. Append 2. Insert 3.Delete 4.Reverse 5.Replacing Character at given index Java Values 41
  • 42. StringBuilder StringBuilder is the same as the StringBuffer class. The StringBuilder class is not synchronized and hence in a single threaded environment, the overhead is less than using a StringBuffer. public class Test { public static void main(String[] args) { String str = “Java"; StringBuffer sbr = new StringBuffer(str); sbr.reverse(); System.out.println(sbr); // conversion from String object to StringBuilder StringBuilder sbl = new StringBuilder(str); sbl.append(“Values"); System.out.println(sbl); } } Java Values 42 Output?
  • 43. StringTokenizer A token is a portion of a string that is separated from another portion of that string by one or more chosen characters (called delimiters). The StringTokenizer class contained in the java.util package can be used to break a string into separate tokens. This is particularly useful in those situations in which we want to read and process one token at a time; the BufferedReader class does not have a method to read one token at a time. Java Values 43
  • 44. Java Values 44 Java Values “Hello world welcome to Java Values” String Tokenizer Token Hello world welcome to Java Values
  • 47.  Statics variable, Method, block, nested class  Constructors default ,no-arg, parameterize  Exceptions in Java Checked –unchecked, exception, error , try-catch-finally-throw-throws, customize exception  String String –Stringbuffer-StringBuilder-String Tokenizer Q & A ??? Java Values 47 For engineering project or live project internship please contact us Mindlabz Software Technology