SlideShare una empresa de Scribd logo
1 de 47
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

Más contenido relacionado

La actualidad más candente (17)

Core Java Introduction | Basics
Core Java Introduction  | BasicsCore Java Introduction  | Basics
Core Java Introduction | Basics
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Java
Java Java
Java
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Introduction to OOP(in java) BY Govind Singh
Introduction to OOP(in java)  BY Govind SinghIntroduction to OOP(in java)  BY Govind Singh
Introduction to OOP(in java) BY Govind Singh
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Oops in java
Oops in javaOops in java
Oops in java
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 

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

UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptxakila m
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsHelen SagayaRaj
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMambikavenkatesh2
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questionsMehtaacademy
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorialrajkamaltibacademy
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxDrYogeshDeshmukh1
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
this keyword in Java.pdf
this keyword in Java.pdfthis keyword in Java.pdf
this keyword in Java.pdfParvizMirzayev2
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programmingshinyduela
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxRAJASEKHARV10
 

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

UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
Lecture 6.pptx
Lecture 6.pptxLecture 6.pptx
Lecture 6.pptx
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
object oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoMobject oriented programming using java, second sem BCA,UoM
object oriented programming using java, second sem BCA,UoM
 
25 java interview questions
25 java interview questions25 java interview questions
25 java interview questions
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Unit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptxUnit No 2 Objects and Classes.pptx
Unit No 2 Objects and Classes.pptx
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
this keyword in Java.pdf
this keyword in Java.pdfthis keyword in Java.pdf
this keyword in Java.pdf
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Static variable
Static  variableStatic  variable
Static variable
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 

Más de Sagar Verma

Java introduction
Java introductionJava introduction
Java introductionSagar Verma
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introductionSagar Verma
 
Springboot introduction
Springboot introductionSpringboot introduction
Springboot introductionSagar Verma
 
2015-16 software project list
2015-16 software project list2015-16 software project list
2015-16 software project listSagar Verma
 
Ns2 new project list
Ns2 new project listNs2 new project list
Ns2 new project listSagar Verma
 
Privacy preserving dm_ppt
Privacy preserving dm_pptPrivacy preserving dm_ppt
Privacy preserving dm_pptSagar Verma
 

Más de Sagar Verma (6)

Java introduction
Java introductionJava introduction
Java introduction
 
Hibernate introduction
Hibernate introductionHibernate introduction
Hibernate introduction
 
Springboot introduction
Springboot introductionSpringboot introduction
Springboot introduction
 
2015-16 software project list
2015-16 software project list2015-16 software project list
2015-16 software project list
 
Ns2 new project list
Ns2 new project listNs2 new project list
Ns2 new project list
 
Privacy preserving dm_ppt
Privacy preserving dm_pptPrivacy preserving dm_ppt
Privacy preserving dm_ppt
 

Último

Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectErbil Polytechnic University
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptNarmatha D
 
Crushers to screens in aggregate production
Crushers to screens in aggregate productionCrushers to screens in aggregate production
Crushers to screens in aggregate productionChinnuNinan
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadaditya806802
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Erbil Polytechnic University
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptbibisarnayak0
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 

Último (20)

Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
Risk Management in Engineering Construction Project
Risk Management in Engineering Construction ProjectRisk Management in Engineering Construction Project
Risk Management in Engineering Construction Project
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.ppt
 
Crushers to screens in aggregate production
Crushers to screens in aggregate productionCrushers to screens in aggregate production
Crushers to screens in aggregate production
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasad
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
Comparative study of High-rise Building Using ETABS,SAP200 and SAFE., SAFE an...
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.ppt
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 

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