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)

Core Java Introduction | Basics
Core Java Introduction  | BasicsCore Java Introduction  | Basics
Core Java Introduction | Basics
Hùng Nguyễn Huy
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Singsys Pte Ltd
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
bindur87
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
Lovely Professional University
 
Java
Java Java
Java
Prabhat gangwar
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
rajveer_Pannu
 
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
prabhat engineering college
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
backdoor
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
Oops in Java
Oops in JavaOops in Java
Oops in Java
malathip12
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
kamal kotecha
 
Oops in java
Oops in javaOops in java
Oops in java
baabtra.com - No. 1 supplier of quality freshers
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
saryu2011
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
Sherihan Anver
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 

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

Object Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for studentsObject Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
Module 1.pptx
Module 1.pptxModule 1.pptx
Module 1.pptx
YakaviBalakrishnan
 
UNIT 3- Java- Inheritance, Multithreading.pptx
UNIT 3- Java- Inheritance, Multithreading.pptxUNIT 3- Java- Inheritance, Multithreading.pptx
UNIT 3- Java- Inheritance, Multithreading.pptx
shilpar780389
 
Unit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfUnit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdf
Arpana Awasthi
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdfClass and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Java Tokens in java program . pptx
Java Tokens in  java program   .    pptxJava Tokens in  java program   .    pptx
Java Tokens in java program . pptx
CmDept
 
Java basic concept
Java basic conceptJava basic concept
Java basic concept
University of Potsdam
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
น้องน๊อต อยากเหยียบดวงจันทร์
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece departmentClass and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
Khizar40
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
Abhijeet Dubey
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
akila m
 
Java ppt Gandhi Ravi ([email protected])
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
Mahika Tutorials
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Soumen Santra
 
Java introduction
Java introductionJava introduction
Java introduction
The icfai university jaipur
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
Ahmed Shawky El-faky
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
bca23189c
 
Object Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for studentsObject Oriented Programming unit 1 content for students
Object Oriented Programming unit 1 content for students
ASHASITTeaching
 
UNIT 3- Java- Inheritance, Multithreading.pptx
UNIT 3- Java- Inheritance, Multithreading.pptxUNIT 3- Java- Inheritance, Multithreading.pptx
UNIT 3- Java- Inheritance, Multithreading.pptx
shilpar780389
 
Unit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdfUnit 2 Part 1 Constructors.pdf
Unit 2 Part 1 Constructors.pdf
Arpana Awasthi
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Class and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdfClass and Object JAVA PROGRAMMING LANG .pdf
Class and Object JAVA PROGRAMMING LANG .pdf
sameer2543ynr
 
Java Tokens in java program . pptx
Java Tokens in  java program   .    pptxJava Tokens in  java program   .    pptx
Java Tokens in java program . pptx
CmDept
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
Class and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece departmentClass and Object.pptx from nit patna ece department
Class and Object.pptx from nit patna ece department
om2348023vats
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
Khizar40
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
akila m
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
Mahika Tutorials
 
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Java basic part 2 : Datatypes Keywords Features Components Security Exceptions
Soumen Santra
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
bca23189c
 
Ad

More from Sagar Verma (6)

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

Recently uploaded (20)

The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for  diesel tank.docxCenter Enamel can Provide Aluminum Dome Roofs for  diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
CenterEnamel
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.pptCOMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
Blood bank management system project report.pdf
Blood bank management system project report.pdfBlood bank management system project report.pdf
Blood bank management system project report.pdf
Kamal Acharya
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Understanding Amplitude Modulation : A Guide
Understanding Amplitude Modulation : A GuideUnderstanding Amplitude Modulation : A Guide
Understanding Amplitude Modulation : A Guide
CircuitDigest
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
First Come First Serve Scheduling in real time operating system.pptx
First Come First Serve Scheduling in real time operating system.pptxFirst Come First Serve Scheduling in real time operating system.pptx
First Come First Serve Scheduling in real time operating system.pptx
KavitaBagewadi2
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
Fundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptxFundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptx
drdebarshi1993
 
Fundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptxFundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptx
drdebarshi1993
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for  diesel tank.docxCenter Enamel can Provide Aluminum Dome Roofs for  diesel tank.docx
Center Enamel can Provide Aluminum Dome Roofs for diesel tank.docx
CenterEnamel
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.pptCOMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
Blood bank management system project report.pdf
Blood bank management system project report.pdfBlood bank management system project report.pdf
Blood bank management system project report.pdf
Kamal Acharya
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Understanding Amplitude Modulation : A Guide
Understanding Amplitude Modulation : A GuideUnderstanding Amplitude Modulation : A Guide
Understanding Amplitude Modulation : A Guide
CircuitDigest
 
First Come First Serve Scheduling in real time operating system.pptx
First Come First Serve Scheduling in real time operating system.pptxFirst Come First Serve Scheduling in real time operating system.pptx
First Come First Serve Scheduling in real time operating system.pptx
KavitaBagewadi2
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
Fundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptxFundamentals of Digital Design_Class_21st May - Copy.pptx
Fundamentals of Digital Design_Class_21st May - Copy.pptx
drdebarshi1993
 
Fundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptxFundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptx
drdebarshi1993
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 

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