Java is a high-level, object-oriented programming language developed by Sun Microsystems in the mid-1990s (now owned by Oracle Corporation). It is widely used for building a variety of applications, including desktop, web, mobile, and enterprise software. Java's design emphasizes portability, simplicity, and security, making it one of the most popular programming languages in the world.
### Importance of Java:
1. **Platform Independence**:
- Java programs can run on any device or operating system that supports the Java Virtual Machine (JVM).
- This "write once, run anywhere" (WORA) capability makes Java applications highly portable.
2. **Object-Oriented Programming (OOP)**:
- Java supports key OOP principles such as inheritance, encapsulation, polymorphism, and abstraction.
- These principles enable developers to create modular and reusable code.
3. **Rich Ecosystem and Libraries**:
- Java has a vast ecosystem of libraries, frameworks, and tools that facilitate development across various domains.
- Popular frameworks like Spring, Hibernate, and Apache Struts streamline development in enterprise environments.
4. **Robustness and Reliability**:
- Java has strong exception handling and type-checking mechanisms that contribute to the robustness and reliability of applications.
5. **Community and Support**:
- Java has a large and active developer community, providing support and resources for learning and troubleshooting.
- Java's extensive documentation and community forums are valuable resources for developers.
6. **Performance**:
- Java's just-in-time (JIT) compilation allows for optimized execution, improving performance.
- Java can handle large-scale applications and complex computations efficiently.
7. **Security**:
- Java's architecture includes features such as runtime security checks and a security manager for safe execution.
- This makes it a preferred choice for developing secure applications.
8. **Enterprise Applications**:
- Java is a dominant language in enterprise development due to its scalability, stability, and compatibility with existing systems.
- Many businesses rely on Java for mission-critical applications.
9. **Career Opportunities**:
- Proficiency in Java opens up many career opportunities, particularly in enterprise development, finance, healthcare, and telecommunications.
10. **Future-Proofing**:
- Java's continuous updates and compatibility with emerging technologies ensure that it remains relevant and future-proof.
Overall, Java's versatility, reliability, and widespread adoption make it an essential language for developers across various industries
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);
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
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!!
}
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);
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.");
}
}