SlideShare a Scribd company logo
1 of 67
public class Main {
public static void main(String[] args) {
String txt = "hello java";
int count=0;
for(int i=0;i<txt.length();i++)
{
switch(txt.charAt(i))
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': count++;
}
}
System.out.println("Vowel count="+count);
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hemlo";
String s4="flag";
System.out.println(s1.compareTo(s2)); // 0 because both are equal
System.out.println(s1.compareTo(s3)); //-1 because "l" is only one time lower than "m
System.out.println(s1.compareTo(s4)); // 2 because "h" is 2 times greater than "f"
}}
No. Method Description
1. char charAt(int index) It returns char value for the particular
index
2. int length() It returns string length
3. String substring(int beginIndex) It returns substring for given begin
index.
4. char charAt(int index) It returns char value for the particular
index
5. public int compareTo(String anotherString)
https://www.javatpoint.com/java-string-compareto
method compares the given string
with the current string
lexicographically. It returns a positive
number, negative number, or 0
6. boolean equals(Object another) It checks the equality of string with the
given object.
7. boolean isEmpty() It checks if string is empty.
8. String concat(String str) It concatenates the specified string.
9. String replace(char old, char new) It replaces all occurrences of the
specified char value.
10. String replace(CharSequence old, CharSequence new) It replaces all occurrences of the
No. Method Description
1. static String equalsIgnoreCase(String another) It compares another string. It
doesn't check case.
2. String[] split(String regex) It returns a split string matching
regex.
3. String[] split(String regex, int limit) It returns a split string matching
regex and limit.
4. int indexOf(int ch) It returns the specified char value
index.
5. int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
6. int indexOf(String substring) It returns the specified substring
index.
7. int indexOf(String substring, int fromIndex) It returns the specified substring
index starting with given index.
8. String toLowerCase() It returns a string in lowercase.
9. String toLowerCase(Locale l) It returns a string in lowercase
using specified locale.
10. String toUpperCase() It returns a string in uppercase.
No. Method Description
1. String toUpperCase(Locale l) It returns a string in uppercase using
specified locale.
2. String trim() It removes beginning and ending spaces
of this string.
3. static String valueOf(int value) It converts given type into string. It is an
overloaded method.
4. String substring(int beginIndex) It returns substring for given begin index.
5. String substring(int beginIndex, int endIndex) It returns substring for given begin index
and end index.
6. boolean contains(CharSequence s) It returns true or false after matching the
sequence of char value.
7. static String join(CharSequence delimiter, CharSequence... elements) It returns a joined string.
8. String[] split(String regex) It returns a split string matching regex.
public class SubstringExample2 {
public static void main(String[] args) {
String s1="Javatpoint";
String substr = s1.substring(0); // Starts with 0 and goes to end
System.out.println(substr);
String substr2 = s1.substring(5,10); // Starts from 5 and goes to 1
0
System.out.println(substr2);
String substr3 = s1.substring(5,15); // Returns Exception
}
}
public class SubstringExample2 {
public static void main(String[] args) {
String s1="Java";
String s2="avJa";
int flag=0;
if(s1.length()==s2.length())
{
for(int i=0;i<s1.length();i++)
if(s2.indexOf(s1.charAt(i))==-1)
{
flag=1;
break;
}
}
else flag=1;
if(flag==1)
System.out.println(" no");
else
System.out.println("yes");
}
• public class Reverse
• {
• public static void main(String[] args) {
• String string = "Dream big";
• //Stores the reverse of given string
• String reversedStr = "";
•
• //Iterate through the string from last and add each character to variable reversedStr
• for(int i = string.length()-1; i >= 0; i--){
• reversedStr = reversedStr + string.charAt(i);
• }
•
• System.out.println("Original string: " + string);
• //Displays the reverse of given string
• System.out.println("Reverse of given string: " + reversedStr);
• }
public class Reverse2
{
public static void main(String[] args) {
String S="hello";
char ch[]=new char[10];
int len=S.length();
for(int i=0;i<S.length();i++)
{
ch[len-i]=S.charAt(i);
}
String reve=new String(ch);
System.out.println(" the reversed string is "+reve);
}
}
public class Palindrome
{
public static void main(String[] args) {
String S="hello";
char ch[]=new char[10];
int len=S.length();
for(int i=0;i<S.length();i++)
ch[len-i]=S.charAt(i);
String reve=new String(ch);
if (reve.equalsIgnoreCase(S))
System.out.println(“Given string is a palindrome”);
else
System.out.println(“Given string is not a palindrome”);
} }
Guess???
public class Example
{
public static void main(String argu[])
{
String str = “I Love Java Programming";
char[] carray = str.toCharArray();
System.out.println("The string is:" + str);
for (int i = 0; i < str.length(); i++)
{ for (int j = i + 1; j < str.length(); j++)
{
if (carray[i] == carray[j])
{
System.out.print(carray[j] + " ");
break; } } } }
public class CountCharacter {
public static void main(String[] args) {
String inputString = “Programs";
char ch = 'o';
int count = 0;
for (int i = 0; i < inputString.length(); i++)
{
if (inputString.charAt(i) == ch) {
count++;
}
}
System.out.println("The character '" + ch + "' found " + count + " times in a string '" + inputString + "'.");
}
}
public static int count(String inputString) {
String[] stringArray = inputString.split("s+"); // splitting the string using space/spaces
return stringArray.length; // returning the length of the array i.e number of words in the
string
}
Constructors of StringBuffer class
1. StringBuffer(): It reserves room for 16 characters without
reallocation
StringBuffer s = new StringBuffer();
2. StringBuffer( int size): It accepts an integer argument that explicitly
sets the size of the buffer.
StringBuffer s = new StringBuffer(20);
3. StringBuffer(String str): It accepts a string argument that sets the
initial contents of the StringBuffer object and reserves room for 16
more characters without reallocation.
StringBuffer s = new StringBuffer("GeeksforGeeks");
import java.io.*;
class STRB {
// main driver method
public static void main(String[] args)
{
// Creating adn storing string by creating object of
// StringBuffer
StringBuffer s = new StringBuffer(“java strings");
int p = s.length();
int q = s.capacity();
System.out.println("Length of string GeeksforGeeks="+ p);
System.out.println("Capacity of string GeeksforGeeks=" + q);
s.append(“executing");
System.out.println(s);
}
} Output Length of string GeeksforGeeks=13
Capacity of string GeeksforGeeks=29
java strings executing
/ /Importing required classes
import java.io.*;
class STRB {
// Main driver method
public static void main(String[] args)
{
// Creating an object of StringBuffer class and
// passing random string
StringBuffer s = new StringBuffer("Geeksfor");
// Usage of append() method
s.append("Geeks");
// Returns GeeksforGeeks
System.out.println(s);
s.append(1);
// Returns GeeksforGeeks1
System.out.println(s);
}
} output: GeeksforGeeks
GeeksforGeeks1
public static void main(String[] args)
{
// Creating an object of StringBuffer class
StringBuffer s = new StringBuffer("GeeksGeeks");
// Inserting element and posistion as an arguments
s.insert(5, "for");
// Returns GeeksforGeeks
System.out.println(s);
s.insert(0, 5);
// Returns 5GeeksforGeeks
System.out.println(s);
s.insert(3, “true”);
// Returns 5GetrueeksforGeeks
System.out.println(s);
s.insert(5, 41.35d);
// Returns 5Getr41.35ueeksforGeeks
System.out.println(s);
s.insert(8, 41.35f);
// Returns 5Getr41.41.3535ueeksforGeeks
System.out.println(s);
// Declaring and initializing character array
char geeks_arr[] = { 'p', 'a', 'w', 'a', 'n' };
// Inserting character array at offset 9
s.insert(2, geeks_arr);
// Returns 5Gpawanetr41.41.3535ueeksforGeeks
System.out.println(s);
}}
Output:
GeeksforGeeks
5GeeksforGeeks
5GetrueeksforGeeks
5Getr41.35ueeksforGeeks
5Getr41.41.3535ueeksforGeeks
5Gpawanetr41.41.3535ueeksforGeeks
class GFG {
// Main driver method
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("GeeksforGeeks");
s.delete(0, 5);
// Returns forGeeks
System.out.println(s);
s.deleteCharAt(7);
// Returns forGeek
System.out.println(s);
}
}
Output:
forGeeks
forGeek
• class GFG {
• // Main driver method
• public static void main(String[] args)
• {
• StringBuffer s = new StringBuffer("GeeksforGeeks");
• s.replace(5, 8, "are");
• // Returns GeeksareGeeks
• System.out.println(s);
• }
• }
• Output
• GeeksareGeeks
StringBuilder Class in Java with Examples
Constructors in Java StringBuilder:
• StringBuilder(): Constructs a string builder with no characters in it and
an initial capacity of 16 characters.
• StringBuilder(int capacity): Constructs a string builder with no
characters in it and an initial capacity specified by the capacity
argument.
• StringBuilder(CharSequence seq): Constructs a string builder that
contains the same characters as the specified CharSequence.
• StringBuilder(String str): Constructs a string builder initialized to the
contents of the specified string.
public class GFG1 {
public static void main(String[] argv)
{
StringBuilder str= new StringBuilder();str.append("GFG");
// print string
System.out.println("String = "+ str.toString());
StringBuilder str1= new StringBuilder("AAAABBBCCCC");
System.out.println("String1 = "+ str1.toString());
StringBuilder str2= new StringBuilder(10);
System.out.println("String2 capacity = "+ str2.capacity());
StringBuilder str3= new StringBuilder(str1.toString());
System.out.println("String3 = "+ str3.toString());
}
}
Output:
String = GFG
String1 = AAAABBBCCCC
String2 capacity = 10
String3 = AAAABBBCCCC
Inheritance
Super class
Sub class
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{
void bark()
{System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[])
{
Animal A=new Animal();
Dog d=new Dog();
A.eat();
d.bark();
d.eat();
A.bark();//illegal
}}
Method overriding: having same method
names+arguments in super and sub classes
class Person{
public String name;
public int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
}
}
public class Student extends Person {
public String branch;
public int Student_id;
public Student(String name, int age, String branch, int Student_id){
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("Branch: "+branch);
System.out.println("Student ID: "+Student_id);
}
public static void main(String[] args) {
Student Stu= new Student("Krishna", 20, “ETC", 1256);
stu. displayStudent();
}
}
Output
Data of the Student class:
Name: Krishna
Age: 20
Branch: ETC
Student ID:1256
• How to Refer a subclass object
• There are two approaches to refer a subclass object. Both have
some advantages/disadvantages over the other. The
declaration affect is seen on methods that are visible at
compile-time.
1.First approach (Referencing using Superclass reference): A
reference variable of a superclass can be used to a refer any
subclass object derived from that superclass. If the methods are
present in SuperClass, but overridden by SubClass, it will be
the overridden method that will be executed.
2.Second approach (Referencing using subclass reference)
: A subclass reference can be used to refer its object.
public static void main(String[] args) {
Person person = new Student("Krishna", 20, "IT", 1256);
person. displayPerson();
}
Data of the Person class:
Name: Krishna
Age: 20
public static void main(String[] args) {
Person person = new Student("Krishna", 20, "IT", 1256);
person. displayStudent();
}
class Base
{
void dispB()
{
System.out.println("Super class " );
}
}
class Derived extends Base
{
void dispD()
{
System.out.println("Sub class ");
}
}
class Demo
{
public static void main(String args[])
{
Base b = new Base();
Derived d=new Derived();
b=d; //superclass reference is holding subclass object
b.dispB();
//b.dispD(); error!!
}
class A
{
A()
{
System.out.println("A's constructor.");
}
}
class B extends A
{
B()
{
System.out.println("B's constructor.");
}
}
class C extends B
{
C()
{
System.out.println("C's constructor.");
}
}
class CallingCons
{
public static void main(String args[])
{
c = new C();
}
}
final
The keyword final can be used in three situations in Java:
• To create the equivalent of a named constant.
• To prevent method overriding
• To prevent Inheritance
To create the equivalent of a named constant: A variable can be declared as
final. Doing so prevents its contents from being modified. This means that
you must initialize a final variable when it is declared. For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3; final
int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
To prevent method overriding: Sometimes, we do not want a superclass method to be overridden in
the subclass. Instead, the same superclass method definition has to be used by every subclass. In such
situation, we can prefix a method with the keyword final as shown below –
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() // ERROR! Can't override.
{
System.out.println("Illegal!");
}
}
To prevent Inheritance: As we have discussed earlier, the subclass is treated as a specialized class and
superclass is most generalized class. During multi-level inheritance, the bottom most class will be with all
the features of real-time and hence it should not be inherited further. In such situations, we can prevent a
particular class from inheriting further, using the keyword final. For example –
final class A
{
// ...
}
class B extends A // ERROR! Can't subclass A
{
// ...
}
Multilevel inhertiance
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
class Cube extends Rectangle {
public void volume() {
System.out.println("Inside volume");
}
}
public class Tester {
public static void main(String[] arguments) {
Cube cube = new Cube();
cube.display();
cube.area();
cube.volume();
}
}
class Person{
public String name;
public int age;
public Person(String name, int age){
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Data of the Person class: ");
System.out.println("Name: "+this.name); //https://www.tutorialspoint.com/compile_java_online.php
System.out.println("Age: "+this.age);
}
}
class Student extends Person {
public String branch;
public int Student_id;
public Student(String name, int age, String branch, int Student_id){
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}
public void display() {
System.out.println("Data of the Student class: ");
System.out.println("Name: "+name);
System.out.println("Age: "+age);
System.out.println("Branch: "+branch);
System.out.println("Student ID: "+Student_id);
}
}
public class test{
public static void main(String[] args) {
Person person = new Student("Krishna", 20, "IT", 1256);
class X
{
int i;
X(int i)
{
this.i=i;
System.out.println(“Created X”);
}
}
class Y extends X
{
int j;
Y(int i, int j)
{
super(i);
this.j = j;
System.out.println("Created Y");
}
}
class Z extends Y
{
int k;
Z(int i, int j, int k)
{
super(i, j);
this.k = k;
System.out.println("Created Z");
}
}
.
• OUTPUT
• ---------------
Created X
---------------
Created X
Created Y
---------------
Created X
Created Y
Created Z
---------------
• DESCRIPTION
• Here we have a created a hierarchy of classes, Z extending Y, which in turn extending from X. When we
observe the output we realize
• that when creating the sub-class object, the super-class constructor is called before the current constructor.
So when object of class Y I
• s created both Created X and Created Y are printed. Similarly when the object of class Z is created Created
X, Created Y and Created Z are printed
Abstract classes
• The abstract keyword is a non-access modifier, used for classes and
methods:
• Abstract class: is a restricted class that cannot be used to create
objects (to access it, it must be inherited from another class).
• Abstract method: can only be used in an abstract class, and it does
not have a body. The body is provided by the subclass (inherited
from).
• An abstract class can have both abstract and regular methods:
Abstract classes
Abstract classes
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
}
}
Output: drawing circle
drawing circle
abstract class Bank{
abstract int getRateOfInterest();
void meth()
{ Output:
System.out.println(“Welcome”); Welcome
}} Rate of Interest is: 7 %
class SBI extends Bank{ Rate of Interest is: 8 %
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
//Bank b=new Bank(); error
b=new SBI();
b.meth();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
Dynamic binding
https://www.javatpoint.com/static-binding-and-dynamic-binding
Method overriding
Interfaces
An interface is defined much like a class. This is the general form of an interface:
access interface name
{
type final-varname1 = value;
type final-varname2 = value;
…………………
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
…………………
}
Few key-points about interface:
When no access specifier is mentioned for an interface, then it is treated as default and the
interface is only available to other members of the package in which it is declared. When an
interface is declared as public, the interface can be used by any other code.
• All the methods declared are abstract methods and hence are not defined inside interface. But, a
class implementing an interface should define all the methods declared inside the interface.
• Variables declared inside of interface are implicitly final and static, meaning they cannot be
changed by the implementing class.
• All the variables declared inside the interface must be initialized.
• All methods and variables are implicitly public
Implementing Interface
interface ICallback
{
void callback(int param);
}
class Client implements ICallback output: callback called with 42
{
public void callback(int p) //note public
{
System.out.println("callback called with " + p);
}
void test()
{
System.out.println(“ordinary method”);
}
}
class TestIface
{
public static void main(String args[])
{
ICallback c = new Client();
c.callback(42);
// c.test() //error!!
} }
interface ICallback
{
void callback(int param);
}
class Client implements ICallback
{
public void callback(int p) //note public
{
System.out.println("callback called with " + p);
}
}
class Client2 implements ICallback
{
public void callback(int p)
{
System.out.println("Another version of ICallBack");
System.out.println("p squared " + p*p);
}
}
class TestIface
{
public static void main(String args[])
{
ICallback x1=new Client(),;
ICallback x2=new Client2()};
x1.callback(5);
x2.callback(5); } } Output: callback called with 5 Another version of ICallBack p squared 25
Variables in interfaces
interface SharedConst
{
int FAIL=0; //these are final by default
int PASS=1;
}
class Result implements SharedConst
{
double mr;
Result(double m)
{
mr=m;
}
int res()
{
if(mr<40)
return FAIL;
else return PASS;
}
}
Extending interfaces
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
class MyClass implements B
{
public void meth1()
{
System.out.println("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
Packages
..DesktopJavaprogramming-with-java-a-primer3e-by-
balagurusamy_compress.pdf
Exception Handling
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an
exception is a run-time error. In computer languages that do not support exception handling, errors must
be checked and handled manually—typically through the use of error codes. This approach is as
cumbersome as it is troublesome. Java’s exception handling avoids these problems and, in the process,
brings run-time error management into the object oriented world.
Exception Handling Fundamentals
A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in
a piece of code. When an exceptional condition arises, an object representing that exception is created
and thrown in the method that caused the error. That method may choose to handle the exception itself,
or pass it on. Either way, at some point, the exception is caught and processed.
Exceptions can be generated by the Java run-time system, or they can be manually generated by your
code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language
or the constraints of the Java execution environment. Manually generated exceptions are typically used
to report some error condition to the caller of a method.
Java exception handling is managed using five keywords:
try: A suspected code segment is kept inside try block.
catch: The remedy is written within catch block.
throw: Whenever run-time error occurs, the code must throw an
exception.
throws: If a method cannot handle any exception by its own and some
subsequent methods
needs to handle them, then a method can be specified with throws keyword
with its declaration.
finally: block should contain the code to be executed after finishing try-
block.
try
{
// block of code to monitor errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
...
….
finally
{
// block of code to be executed after try block ends
}
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Output:
Division by zero.
After catch statement
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = 0; // or take 0 as input from keyboard
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} c
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Programing with java for begniers  .pptx

More Related Content

Similar to Programing with java for begniers .pptx

131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)Tak Lee
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper classSimoniShah6
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Ayes Chinmay
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfRohitkumarYadav80
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdfakkhan101
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Featurexcoda
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................suchitrapoojari984
 
Write a class of static methods that accomplish the following tasks. .docx
 Write a class of static methods that accomplish the following tasks. .docx Write a class of static methods that accomplish the following tasks. .docx
Write a class of static methods that accomplish the following tasks. .docxajoy21
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdffreddysarabia1
 
this is the code using array i want with stack or linked list  or .docx
this is the code using array i want with stack or linked list  or .docxthis is the code using array i want with stack or linked list  or .docx
this is the code using array i want with stack or linked list  or .docxabhi353063
 
Java programs
Java programsJava programs
Java programsjojeph
 

Similar to Programing with java for begniers .pptx (20)

131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
java-programming.pdf
java-programming.pdfjava-programming.pdf
java-programming.pdf
 
JAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdfJAVA PRACTICE QUESTIONS v1.4.pdf
JAVA PRACTICE QUESTIONS v1.4.pdf
 
OrderTest.javapublic class OrderTest {       Get an arra.pdf
OrderTest.javapublic class OrderTest {         Get an arra.pdfOrderTest.javapublic class OrderTest {         Get an arra.pdf
OrderTest.javapublic class OrderTest {       Get an arra.pdf
 
Chapter 7 String
Chapter 7 StringChapter 7 String
Chapter 7 String
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
Java 5 New Feature
Java 5 New FeatureJava 5 New Feature
Java 5 New Feature
 
Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................Unit-2.Arrays and Strings.pptx.................
Unit-2.Arrays and Strings.pptx.................
 
Write a class of static methods that accomplish the following tasks. .docx
 Write a class of static methods that accomplish the following tasks. .docx Write a class of static methods that accomplish the following tasks. .docx
Write a class of static methods that accomplish the following tasks. .docx
 
Java programs
Java programsJava programs
Java programs
 
Strings
StringsStrings
Strings
 
String notes
String notesString notes
String notes
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
 
this is the code using array i want with stack or linked list  or .docx
this is the code using array i want with stack or linked list  or .docxthis is the code using array i want with stack or linked list  or .docx
this is the code using array i want with stack or linked list  or .docx
 
Java programs
Java programsJava programs
Java programs
 
Strings.ppt
Strings.pptStrings.ppt
Strings.ppt
 

Recently uploaded

SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingrknatarajan
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...ranjana rawat
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 

Recently uploaded (20)

SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 

Programing with java for begniers .pptx

  • 1. public class Main { public static void main(String[] args) { String txt = "hello java"; int count=0; for(int i=0;i<txt.length();i++) { switch(txt.charAt(i)) { case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case 'u': count++; } } System.out.println("Vowel count="+count);
  • 2. public class CompareToExample{ public static void main(String args[]){ String s1="hello"; String s2="hello"; String s3="hemlo"; String s4="flag"; System.out.println(s1.compareTo(s2)); // 0 because both are equal System.out.println(s1.compareTo(s3)); //-1 because "l" is only one time lower than "m System.out.println(s1.compareTo(s4)); // 2 because "h" is 2 times greater than "f" }}
  • 3. No. Method Description 1. char charAt(int index) It returns char value for the particular index 2. int length() It returns string length 3. String substring(int beginIndex) It returns substring for given begin index. 4. char charAt(int index) It returns char value for the particular index 5. public int compareTo(String anotherString) https://www.javatpoint.com/java-string-compareto method compares the given string with the current string lexicographically. It returns a positive number, negative number, or 0 6. boolean equals(Object another) It checks the equality of string with the given object. 7. boolean isEmpty() It checks if string is empty. 8. String concat(String str) It concatenates the specified string. 9. String replace(char old, char new) It replaces all occurrences of the specified char value. 10. String replace(CharSequence old, CharSequence new) It replaces all occurrences of the
  • 4. No. Method Description 1. static String equalsIgnoreCase(String another) It compares another string. It doesn't check case. 2. String[] split(String regex) It returns a split string matching regex. 3. String[] split(String regex, int limit) It returns a split string matching regex and limit. 4. int indexOf(int ch) It returns the specified char value index. 5. int indexOf(int ch, int fromIndex) It returns the specified char value index starting with given index. 6. int indexOf(String substring) It returns the specified substring index. 7. int indexOf(String substring, int fromIndex) It returns the specified substring index starting with given index. 8. String toLowerCase() It returns a string in lowercase. 9. String toLowerCase(Locale l) It returns a string in lowercase using specified locale. 10. String toUpperCase() It returns a string in uppercase.
  • 5. No. Method Description 1. String toUpperCase(Locale l) It returns a string in uppercase using specified locale. 2. String trim() It removes beginning and ending spaces of this string. 3. static String valueOf(int value) It converts given type into string. It is an overloaded method. 4. String substring(int beginIndex) It returns substring for given begin index. 5. String substring(int beginIndex, int endIndex) It returns substring for given begin index and end index. 6. boolean contains(CharSequence s) It returns true or false after matching the sequence of char value. 7. static String join(CharSequence delimiter, CharSequence... elements) It returns a joined string. 8. String[] split(String regex) It returns a split string matching regex.
  • 6. public class SubstringExample2 { public static void main(String[] args) { String s1="Javatpoint"; String substr = s1.substring(0); // Starts with 0 and goes to end System.out.println(substr); String substr2 = s1.substring(5,10); // Starts from 5 and goes to 1 0 System.out.println(substr2); String substr3 = s1.substring(5,15); // Returns Exception } }
  • 7. public class SubstringExample2 { public static void main(String[] args) { String s1="Java"; String s2="avJa"; int flag=0; if(s1.length()==s2.length()) { for(int i=0;i<s1.length();i++) if(s2.indexOf(s1.charAt(i))==-1) { flag=1; break; } } else flag=1; if(flag==1) System.out.println(" no"); else System.out.println("yes"); }
  • 8.
  • 9. • public class Reverse • { • public static void main(String[] args) { • String string = "Dream big"; • //Stores the reverse of given string • String reversedStr = ""; • • //Iterate through the string from last and add each character to variable reversedStr • for(int i = string.length()-1; i >= 0; i--){ • reversedStr = reversedStr + string.charAt(i); • } • • System.out.println("Original string: " + string); • //Displays the reverse of given string • System.out.println("Reverse of given string: " + reversedStr); • }
  • 10. public class Reverse2 { public static void main(String[] args) { String S="hello"; char ch[]=new char[10]; int len=S.length(); for(int i=0;i<S.length();i++) { ch[len-i]=S.charAt(i); } String reve=new String(ch); System.out.println(" the reversed string is "+reve); } }
  • 11. public class Palindrome { public static void main(String[] args) { String S="hello"; char ch[]=new char[10]; int len=S.length(); for(int i=0;i<S.length();i++) ch[len-i]=S.charAt(i); String reve=new String(ch); if (reve.equalsIgnoreCase(S)) System.out.println(“Given string is a palindrome”); else System.out.println(“Given string is not a palindrome”); } }
  • 12. Guess??? public class Example { public static void main(String argu[]) { String str = “I Love Java Programming"; char[] carray = str.toCharArray(); System.out.println("The string is:" + str); for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j < str.length(); j++) { if (carray[i] == carray[j]) { System.out.print(carray[j] + " "); break; } } } }
  • 13. public class CountCharacter { public static void main(String[] args) { String inputString = “Programs"; char ch = 'o'; int count = 0; for (int i = 0; i < inputString.length(); i++) { if (inputString.charAt(i) == ch) { count++; } } System.out.println("The character '" + ch + "' found " + count + " times in a string '" + inputString + "'."); } }
  • 14. public static int count(String inputString) { String[] stringArray = inputString.split("s+"); // splitting the string using space/spaces return stringArray.length; // returning the length of the array i.e number of words in the string }
  • 15. Constructors of StringBuffer class 1. StringBuffer(): It reserves room for 16 characters without reallocation StringBuffer s = new StringBuffer(); 2. StringBuffer( int size): It accepts an integer argument that explicitly sets the size of the buffer. StringBuffer s = new StringBuffer(20); 3. StringBuffer(String str): It accepts a string argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation. StringBuffer s = new StringBuffer("GeeksforGeeks");
  • 16.
  • 17. import java.io.*; class STRB { // main driver method public static void main(String[] args) { // Creating adn storing string by creating object of // StringBuffer StringBuffer s = new StringBuffer(“java strings"); int p = s.length(); int q = s.capacity(); System.out.println("Length of string GeeksforGeeks="+ p); System.out.println("Capacity of string GeeksforGeeks=" + q); s.append(“executing"); System.out.println(s); } } Output Length of string GeeksforGeeks=13 Capacity of string GeeksforGeeks=29 java strings executing
  • 18. / /Importing required classes import java.io.*; class STRB { // Main driver method public static void main(String[] args) { // Creating an object of StringBuffer class and // passing random string StringBuffer s = new StringBuffer("Geeksfor"); // Usage of append() method s.append("Geeks"); // Returns GeeksforGeeks System.out.println(s); s.append(1); // Returns GeeksforGeeks1 System.out.println(s); } } output: GeeksforGeeks GeeksforGeeks1
  • 19. public static void main(String[] args) { // Creating an object of StringBuffer class StringBuffer s = new StringBuffer("GeeksGeeks"); // Inserting element and posistion as an arguments s.insert(5, "for"); // Returns GeeksforGeeks System.out.println(s); s.insert(0, 5); // Returns 5GeeksforGeeks System.out.println(s); s.insert(3, “true”); // Returns 5GetrueeksforGeeks System.out.println(s); s.insert(5, 41.35d); // Returns 5Getr41.35ueeksforGeeks System.out.println(s);
  • 20. s.insert(8, 41.35f); // Returns 5Getr41.41.3535ueeksforGeeks System.out.println(s); // Declaring and initializing character array char geeks_arr[] = { 'p', 'a', 'w', 'a', 'n' }; // Inserting character array at offset 9 s.insert(2, geeks_arr); // Returns 5Gpawanetr41.41.3535ueeksforGeeks System.out.println(s); }} Output: GeeksforGeeks 5GeeksforGeeks 5GetrueeksforGeeks 5Getr41.35ueeksforGeeks 5Getr41.41.3535ueeksforGeeks 5Gpawanetr41.41.3535ueeksforGeeks
  • 21. class GFG { // Main driver method public static void main(String[] args) { StringBuffer s = new StringBuffer("GeeksforGeeks"); s.delete(0, 5); // Returns forGeeks System.out.println(s); s.deleteCharAt(7); // Returns forGeek System.out.println(s); } } Output: forGeeks forGeek
  • 22. • class GFG { • // Main driver method • public static void main(String[] args) • { • StringBuffer s = new StringBuffer("GeeksforGeeks"); • s.replace(5, 8, "are"); • // Returns GeeksareGeeks • System.out.println(s); • } • } • Output • GeeksareGeeks
  • 23. StringBuilder Class in Java with Examples Constructors in Java StringBuilder: • StringBuilder(): Constructs a string builder with no characters in it and an initial capacity of 16 characters. • StringBuilder(int capacity): Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument. • StringBuilder(CharSequence seq): Constructs a string builder that contains the same characters as the specified CharSequence. • StringBuilder(String str): Constructs a string builder initialized to the contents of the specified string.
  • 24. public class GFG1 { public static void main(String[] argv) { StringBuilder str= new StringBuilder();str.append("GFG"); // print string System.out.println("String = "+ str.toString()); StringBuilder str1= new StringBuilder("AAAABBBCCCC"); System.out.println("String1 = "+ str1.toString()); StringBuilder str2= new StringBuilder(10); System.out.println("String2 capacity = "+ str2.capacity()); StringBuilder str3= new StringBuilder(str1.toString()); System.out.println("String3 = "+ str3.toString()); } } Output: String = GFG String1 = AAAABBBCCCC String2 capacity = 10 String3 = AAAABBBCCCC
  • 26.
  • 27.
  • 28.
  • 30. class Animal{ void eat() {System.out.println("eating...");} } class Dog extends Animal{ void bark() {System.out.println("barking...");} } class TestInheritance{ public static void main(String args[]) { Animal A=new Animal(); Dog d=new Dog(); A.eat(); d.bark(); d.eat(); A.bark();//illegal }}
  • 31. Method overriding: having same method names+arguments in super and sub classes
  • 32.
  • 33. class Person{ public String name; public int age; public Person(String name, int age){ this.name = name; this.age = age; } public void displayPerson() { System.out.println("Data of the Person class: "); System.out.println("Name: "+this.name); System.out.println("Age: "+this.age); } }
  • 34. public class Student extends Person { public String branch; public int Student_id; public Student(String name, int age, String branch, int Student_id){ super(name, age); this.branch = branch; this.Student_id = Student_id; } public void displayStudent() { System.out.println("Data of the Student class: "); System.out.println("Name: "+name); System.out.println("Age: "+age); System.out.println("Branch: "+branch); System.out.println("Student ID: "+Student_id); }
  • 35. public static void main(String[] args) { Student Stu= new Student("Krishna", 20, “ETC", 1256); stu. displayStudent(); } } Output Data of the Student class: Name: Krishna Age: 20 Branch: ETC Student ID:1256
  • 36. • How to Refer a subclass object • There are two approaches to refer a subclass object. Both have some advantages/disadvantages over the other. The declaration affect is seen on methods that are visible at compile-time. 1.First approach (Referencing using Superclass reference): A reference variable of a superclass can be used to a refer any subclass object derived from that superclass. If the methods are present in SuperClass, but overridden by SubClass, it will be the overridden method that will be executed. 2.Second approach (Referencing using subclass reference) : A subclass reference can be used to refer its object.
  • 37. public static void main(String[] args) { Person person = new Student("Krishna", 20, "IT", 1256); person. displayPerson(); } Data of the Person class: Name: Krishna Age: 20
  • 38. public static void main(String[] args) { Person person = new Student("Krishna", 20, "IT", 1256); person. displayStudent(); }
  • 39. class Base { void dispB() { System.out.println("Super class " ); } } class Derived extends Base { void dispD() { System.out.println("Sub class "); } } class Demo { public static void main(String args[]) { Base b = new Base(); Derived d=new Derived(); b=d; //superclass reference is holding subclass object b.dispB(); //b.dispD(); error!! }
  • 40. class A { A() { System.out.println("A's constructor."); } } class B extends A { B() { System.out.println("B's constructor."); } } class C extends B { C() { System.out.println("C's constructor."); } }
  • 41. class CallingCons { public static void main(String args[]) { c = new C(); } }
  • 42. final The keyword final can be used in three situations in Java: • To create the equivalent of a named constant. • To prevent method overriding • To prevent Inheritance To create the equivalent of a named constant: A variable can be declared as final. Doing so prevents its contents from being modified. This means that you must initialize a final variable when it is declared. For example: final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; final int FILE_QUIT = 5;
  • 43. To prevent method overriding: Sometimes, we do not want a superclass method to be overridden in the subclass. Instead, the same superclass method definition has to be used by every subclass. In such situation, we can prefix a method with the keyword final as shown below – class A { final void meth() { System.out.println("This is a final method."); } } class B extends A { void meth() // ERROR! Can't override. { System.out.println("Illegal!"); } } To prevent Inheritance: As we have discussed earlier, the subclass is treated as a specialized class and superclass is most generalized class. During multi-level inheritance, the bottom most class will be with all the features of real-time and hence it should not be inherited further. In such situations, we can prevent a particular class from inheriting further, using the keyword final. For example – final class A { // ... } class B extends A // ERROR! Can't subclass A { // ... }
  • 44. Multilevel inhertiance class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }}
  • 45. class Shape { public void display() { System.out.println("Inside display"); } } class Rectangle extends Shape { public void area() { System.out.println("Inside area"); } } class Cube extends Rectangle { public void volume() { System.out.println("Inside volume"); } }
  • 46. public class Tester { public static void main(String[] arguments) { Cube cube = new Cube(); cube.display(); cube.area(); cube.volume(); } }
  • 47. class Person{ public String name; public int age; public Person(String name, int age){ this.name = name; this.age = age; } public void display() { System.out.println("Data of the Person class: "); System.out.println("Name: "+this.name); //https://www.tutorialspoint.com/compile_java_online.php System.out.println("Age: "+this.age); } } class Student extends Person { public String branch; public int Student_id; public Student(String name, int age, String branch, int Student_id){ super(name, age); this.branch = branch; this.Student_id = Student_id; } public void display() { System.out.println("Data of the Student class: "); System.out.println("Name: "+name); System.out.println("Age: "+age); System.out.println("Branch: "+branch); System.out.println("Student ID: "+Student_id); } } public class test{ public static void main(String[] args) { Person person = new Student("Krishna", 20, "IT", 1256);
  • 48. class X { int i; X(int i) { this.i=i; System.out.println(“Created X”); } }
  • 49. class Y extends X { int j; Y(int i, int j) { super(i); this.j = j; System.out.println("Created Y"); } } class Z extends Y { int k; Z(int i, int j, int k) { super(i, j); this.k = k; System.out.println("Created Z"); } } .
  • 50. • OUTPUT • --------------- Created X --------------- Created X Created Y --------------- Created X Created Y Created Z --------------- • DESCRIPTION • Here we have a created a hierarchy of classes, Z extending Y, which in turn extending from X. When we observe the output we realize • that when creating the sub-class object, the super-class constructor is called before the current constructor. So when object of class Y I • s created both Created X and Created Y are printed. Similarly when the object of class Z is created Created X, Created Y and Created Z are printed
  • 51. Abstract classes • The abstract keyword is a non-access modifier, used for classes and methods: • Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class). • Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from). • An abstract class can have both abstract and regular methods:
  • 53. Abstract classes abstract class Shape{ abstract void draw(); } //In real scenario, implementation is provided by others i.e. unknown by end user class Rectangle extends Shape{ void draw(){System.out.println("drawing rectangle");} } class Circle1 extends Shape{ void draw(){System.out.println("drawing circle");} } //In real scenario, method is called by programmer or user class TestAbstraction1{ public static void main(String args[]){ Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method s.draw(); } } Output: drawing circle drawing circle
  • 54. abstract class Bank{ abstract int getRateOfInterest(); void meth() { Output: System.out.println(“Welcome”); Welcome }} Rate of Interest is: 7 % class SBI extends Bank{ Rate of Interest is: 8 % int getRateOfInterest(){return 7;} } class PNB extends Bank{ int getRateOfInterest(){return 8;} } class TestBank{ public static void main(String args[]){ Bank b; //Bank b=new Bank(); error b=new SBI(); b.meth(); System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %"); b=new PNB(); System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
  • 56. Interfaces An interface is defined much like a class. This is the general form of an interface: access interface name { type final-varname1 = value; type final-varname2 = value; ………………… return-type method-name1(parameter-list); return-type method-name2(parameter-list); ………………… } Few key-points about interface: When no access specifier is mentioned for an interface, then it is treated as default and the interface is only available to other members of the package in which it is declared. When an interface is declared as public, the interface can be used by any other code. • All the methods declared are abstract methods and hence are not defined inside interface. But, a class implementing an interface should define all the methods declared inside the interface. • Variables declared inside of interface are implicitly final and static, meaning they cannot be changed by the implementing class. • All the variables declared inside the interface must be initialized. • All methods and variables are implicitly public
  • 57. Implementing Interface interface ICallback { void callback(int param); } class Client implements ICallback output: callback called with 42 { public void callback(int p) //note public { System.out.println("callback called with " + p); } void test() { System.out.println(“ordinary method”); } } class TestIface { public static void main(String args[]) { ICallback c = new Client(); c.callback(42); // c.test() //error!! } }
  • 58. interface ICallback { void callback(int param); } class Client implements ICallback { public void callback(int p) //note public { System.out.println("callback called with " + p); } } class Client2 implements ICallback { public void callback(int p) { System.out.println("Another version of ICallBack"); System.out.println("p squared " + p*p); } } class TestIface { public static void main(String args[]) { ICallback x1=new Client(),; ICallback x2=new Client2()}; x1.callback(5); x2.callback(5); } } Output: callback called with 5 Another version of ICallBack p squared 25
  • 59. Variables in interfaces interface SharedConst { int FAIL=0; //these are final by default int PASS=1; } class Result implements SharedConst { double mr; Result(double m) { mr=m; } int res() { if(mr<40) return FAIL; else return PASS; } }
  • 60. Extending interfaces interface A { void meth1(); void meth2(); } interface B extends A { void meth3(); } class MyClass implements B { public void meth1() { System.out.println("Implement meth1()."); } public void meth2() { System.out.println("Implement meth2()."); } public void meth3() { System.out.println("Implement meth3().");
  • 62. Exception Handling An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception handling, errors must be checked and handled manually—typically through the use of error codes. This approach is as cumbersome as it is troublesome. Java’s exception handling avoids these problems and, in the process, brings run-time error management into the object oriented world. Exception Handling Fundamentals A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method.
  • 63. Java exception handling is managed using five keywords: try: A suspected code segment is kept inside try block. catch: The remedy is written within catch block. throw: Whenever run-time error occurs, the code must throw an exception. throws: If a method cannot handle any exception by its own and some subsequent methods needs to handle them, then a method can be specified with throws keyword with its declaration. finally: block should contain the code to be executed after finishing try- block.
  • 64. try { // block of code to monitor errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } ... …. finally { // block of code to be executed after try block ends }
  • 65. class Exc2 { public static void main(String args[]) { int d, a; try { d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { System.out.println("Division by zero."); } System.out.println("After catch statement."); } } Output: Division by zero. After catch statement
  • 66. class MultiCatch { public static void main(String args[]) { try { int a = 0; // or take 0 as input from keyboard System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } c catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); } }