flow control statements
[Link]
[Link]
break
is used to cause premature termination of the loop either
conditionally or unconditionally
continue
is used to skip current iteration in the loop and jump to the
next iteration
Linear loop
Quadratic loops
Input:
5
Output:
*****
*****
*****
*****
*****
ASCII Character Set
1963
A-Z --------->127
A-65
B-66
C-67
......
Z-99
a-z------->97-122
A-Z------>65-90
space---->32
Array
Derived Types
Store multiples of the same type under a single name.
Array
Index
int arr[];
java style declaration
datatype[] array_naame
int[] arr;
compile time initialization
datatype array_name[] ={va1,val2,val3};
int arr[] = {10,20,30};
0 1 2
String strArr[] = {"Po", "Tigress" , "Shifu"};
0 1 2
char charArr[] = {'a' , 'c' ,'c','i'}
int arr[] =new int[10];
Disadvantages of arrays in java
they are static in nature
Expand or Shrink
int arr[] = new int [10];
ArrayList
Java Collection Framework
stacks,queues, ArrayList ,HashMap,
Input:
size
Array elements
Input
5
10 20 30 40 50
Input:
7
abcdef g
char charArray[] = new char[n] ; //declaration
for(int i =0 ;i<n;i++){
charArray [i]=[Link]().charAt(0);
}
for-each loop:
syntax
--------- for(datatype var_name:
collection_name)
--------->([Link])
Arrays class contains some very useful utility static
methods that can applied on array for
Syntax:(arrays static methods so we can create objects)
-----------
Arrays.<method>
[Link]() -->method
[Link]()
To sort the given array in the ascending order of the values.
In-Value
Arrays.fill()
[Link](arr1,arr2)--->boolean
true ,both arrays are equal in terms of values
false,otherwise
[Link](arr1,arr2)-->int
value based comparison
1 --> if array1 is greater than array2
0 --> if array1 is equal to array2
-1 -->if array1 is less than array2
the first differing value decides
{1,2,3,4,5} arr1
{1,2,5,4,3} arr2
Unicode
ASCII -->127
Extended ASCII --> 255
UNICODE Character Set
Python is 100% object oriented
Wrapping primitive value in the form of objects Every
primitive is having a corresponding wrapper class, you can
treat
the primitive value as an object using wrapper classes.
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
method or a variable ----------->camelCase
classes
TitleCase
System
String
Math
ArrayList
charAt()
-----------------------------------------------------------------
Compiling and Running a java Program
JDK, JRE and JVM
Identifiers Data types
Operators
Conditional Statements
Loops
Arrays
-------------------------------------------------------
Multi denmention Arrays
2-D Arrays
3-D Arrays
2-D Arrays :-
---------------
Syntax for a 2-D array declaration in java
datatype [][] array_name = new data type[r][c]
here 2 pairs of square brackets represent two dimensions
Rows and Columns
Ex : int [] [] twoArray = new int[][]
A 2-D array in java can be created in a lot of ways
1. 2-D array in Java can be created in a lot of ways
Ex: int[][] arr = {{10,20},{30,40},{50,60}};
Ex: char[][] arr={{'a',b'},{'c','d'},{'e','f'}};
Ex: String[][] arr={{"hh","aaa","aass"},{"sas","asss","asaa"}};
Ex:double[][] arr={{2.2,3.3},{4.4,5.5}{6.6,7.7}};
//index 0 1 0 1 0 1
int[][] arr ={{10,20},{20,30},{30,40}};
0 1 2
First line contains 2 values R and C denoting Rows and
Columns
The next R lines contains C values in each line
Ex:
24
10 20 30 40
50 50 70 80
ex:
32
10 20
30 40
50 60
import books to learn java:
-------------------------------------
Java - Complete Reference
Java - One Step Ahead ----> Anita Seth and [Link]
Clean Code -->Robert [Link]
Taocp --> The Art of Computer Programming form Donald
Knuth
Father of Analysis of Algorithms
--------------------------------------------------------------------------------
-----------
Arrays duplication:
import [Link];
import [Link];
class twoDArray{
public static void main(String[] args){
int[] arr ={-1,5,32,6,22,-17};
int [] brr = [Link]();
[Link](arr);
[Link]([Link](arr));
[Link]([Link](brr));
}
}
--------------------------------------------------------------------------------
---------
auto boxing and unboxing
class twoDArray{
//autoboxing
public static void main(String[] args){
int a =10;
Integer number = a;
[Link](number instanceof Integer);
//auto unboxing
int b = number;
}
}
--------------------------------------------------------------------------------
----------
Strings in java
-Java Strings are immutable
-Strings index starts from 0
[Link](i)
-
--------------------------------------------------------------------------------
---------
Convert the string to a character Array
change the value at the index
convert the character array back to string
For each loop will not work
S="Hello World"
for(int i:
String -> character Array
[Link]()
This is java Programming
--------------------------------------------------------------------------------
-----------------------
contains()
check if a string contains another string
s1="hello world"
s2= "llo"
[Link](s2) ---> true
--------------------------------------------------------------------------
Strings:
----------
* Generally, string is a sequence of characters.
But in java, string is an object that represents
a sequence of characters.
* The [Link] class is used to create
string object.
* Strings are immutable in nature, i.e once an
object created that object doesn’t allow any
changes to it.
* String is basically an object that represents
sequence of char values. An array of characters
works the same as java string. For example:
=================================
char[] ch={'j','a','v','a'};
String s=new String(ch);
is same as:
---------------
String s="javA";
=================================
* There are two ways to create String object:
1. By string literal
2. By new keyword
String Literal:
-------------------
* Java String literal is created by using double quotes. For
Example:
------------
String s="welcome";
* The advantage of string literal usage is memory efficiency.
By new keyword
String s=new String("Welcome");
Example:
-------------
class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to
//string
String s3=new String("example");//creating java
//string by new keyword
[Link](s1);
[Link](s2);
[Link](s3);
}
}
--------------------------------------------------------------------------------
-
Output
||========||
|| java ||
|| strings ||
|| example||
||========||
--------------------------------------------------------------------------------
-
String handling methods:
======================
||--------------||----------------------------------------||--------------------
----------------------------||--------------------------------------------------
-----||
|| S.N || Method name || General form
|| Example ||
||--------------||----------------------------------------||--------------------
----------------------------||--------------------------------------------------
-----||
1 length() int length( )
String s = new String (“hello”);
[Link]([Link]());
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
------
2 charAt( ) char charAt(int
where) char ch;
ch = "abc".charAt(1);
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
------
3 getChars( ) void getChars
(int sourceStart,
int sourceEnd,
char target[ ], int
targetStart)
String s = "This is a demo of the
getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[10];
[Link](start, end, buf, 0);
[Link](buf);
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
------
4 equals( ) boolean
equals(Object str)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-----
5 equalsIgnoreCase( ) boolean
equalsIgnoreCase
(String str)
String s1 = "Hello";
String s2 = "hello";
[Link](“s1 and s2 are
equal " +[Link](s2));
[Link]("s1 and s2 are
equal" +[Link](s4));
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-----
6 substring( ) String
substring(int startIndex)
String
substring(int startIndex,int endIndex)
String s1=”hello java”;
[Link](substring
(1,4));
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
----
7 concat( ) String concat(String
str) String s1 = "one";
String s2 = [Link]("two");
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
----
8 replace( ) String replace(char
original,
char replacement)
String s = "Hello".replace('l', 'w');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-------
9 trim( ) String trim( )
String s = " Hello World ";
[Link]([Link]());
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-------
10 toLowerCase( )
toUpperCase( )
String toLowerCase( )
String toUpperCase( )
String s1 = " HELLO";
String s2=”hello”;
[Link]([Link]( ));
[Link]([Link]( ));
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-------
StringBuffer:
------------------
* StringBuffer is a peer class of String that provides much of
the functionality of strings.
* String represents fixed-length, immutable character
sequences. In contrast, StringBuffer
represents growable and writable character sequences.
* General form of StringBuffer
==> StringBuffer sb=new StringBuffer(“Hello World”);
* The StringBuffer class exists in “[Link]” package.
* StringBuffer is immutable that means, any changes
performed to the StringBuffer object
that changes will reflect on the object.
* StringBuffer Methods:
--------------------------------
||==========================||======================
========||=========================================
=||
||S.N Method name ||General form
||Example ||
||==========================||======================
========||=========================================
=||
|| 1 length( ) || int length( )
|| StringBuffer sb = newStringBuffer("Hello"); ||
[Link]("buffer = " + sb);
[Link]("length="+[Link]());
[Link]("capacity="+ [Link]());
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
------
2 capacity( ) int capacity( )
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-----
3 ensure
Capacity( )
void ensureCapacity(int
capacity)
[Link](30));
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-----
4 setLength( ) void setLength(int len)
StringBuffer sb = new StringBuffer("Hello");
[Link]("buffer before = " + sb);
[Link]("charAt(1) before = " +
[Link](1));
[Link](1, 'i');
[Link](2);
[Link]("buffer after = " + sb);
[Link]("charAt(1) after = " +
[Link](1));
5 charAt( ) char charAt(int where)
6 setCharAt( ) void setCharAt(int where,
char ch)
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-------
7 getChars( ) void getChars(int
sourceStart, int sourceEnd, char target[ ],int targetStart)
StringBuffer sb=new StringBuffer("This is a demo
of the getChars method.");
int start = 10;
int end = 14;
char buf[] = new char[10];
[Link](start, end, buf, 0);
[Link](buf );
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-------
8 append() StringBuffer append(String
str)
StringBuffer
append(int num) StringBuffer sb = new StringBuffer(40);
s=
[Link]("is a number");
[Link](s);
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
------
9 insert( ) StringBuffer insert(int
index, String str)
StringBuffer insert(int
index, char ch)
StringBuffer sb = new StringBuffer("I Java!");
[Link](2, "like ");
[Link](sb);
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
------
10 reverse( ) StringBuffer reverse( )
StringBuffer s = new StringBuffer("abcdef");
[Link](s);
[Link]();
[Link](s);
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
------
11 delete( ) and
deleteCharAt()
StringBuffer delete(int
startIndex, int endIndex)
StringBuffer deleteCharAt(int
loc)
StringBuffer sb = new StringBuffer("This is a test.");
[Link](4, 7);
[Link]("After delete: " + sb);
[Link](0);
[Link]("After deleteCharAt: " + sb);
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
------
12 replace( ) StringBuffer replace(int startIndex,
int endIndex, String str)
StringBuffer sb = new StringBuffer("This is a test.");
[Link](5, 7, "was");
[Link]("After replace: " + sb);
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
------
13 substring( ) String substring(int startIndex)
String substring(int startIndex, int
endIndex)
StringBuffer sb = new StringBuffer(”hello java”);
String s= substring(1,4);
[Link](s);
==================================================
==================================================
==
******-------*******
arbitrary number of arguments in java:
--------------------------------------------------------
It is typically referred to as "variable-length arguments" or
"varargs." Varargs allow you to pass a variable number of
arguments of the same type to a method. This is achieved
using ellipsis (...) in the method parameter declaration.
Syntax:
----------
accessModifier returnType methodName(parameterList) {
// Method body or implementation
}
accessModifier: This specifies the visibility or accessibility
of the method. It can be one of the following access
modifiers:
public: The method is accessible from any class.
private: The method is accessible only within the same
class.
protected: The method is accessible within the same class
and its subclasses.
Package-private (default): If no access modifier is specified,
the method is accessible within the same package.
returnType: This specifies the data type of the value that
the method will return. It can be any valid data type in Java,
or void if the method does not return any value.
methodName: This is the name of the method, which
should follow Java's naming conventions.
parameterList: This is a list of parameters enclosed in
parentheses. Parameters are variables that the method can
use. If there are no parameters, you still need to include
empty parentheses.
Method body or implementation: This is the block of code
enclosed within curly braces {} that defines what the
method does. It contains statements and can utilize the
parameters to perform a specific task.
Terminology - Some commonly used words in OOPS;
--------------------------------------------------------------------------------
1-class
2-object
3-instance
4-method
5-overloading
6-overriding
7-static / class variable
8-instance variable
9-constructor
10-modifiers
11-access modifiers
12-non-access modifiers
13-abstract class
14-interface
15-this keyword
16-super keyword
17-inheritance
18-polymorphism
19-data abstraction
20-encapsulation
21-package
22-scope of variables
23-method signature
24-annotation
25-exception
26-comparator
27-parametric
constructor
-------------------------------------------------------------------------------
1)class
------
A blueprint.
object --->A real building
A class is a collection of members.
Member variables / fields.
properties / attributes
Member functions / Methods
actions / behaviors
Noun,pronoun,verb,adverb,
Cat
properties
---------
name
breed
color
----------------------------------
Pillars of OOPS
-Abstraction
-Encapsulation
-Inheritance
-Polymorphism
-------------------------------------
Data Abstraction:
------------------------
ex:driving a car
how to work only know
Encapsulation:
---------------------
-Wapping up data under a single unit
-meaning="data hiding"
-it is data manipulation.
-private & protected access modifiers and using nested
classes.
-it is accessed by the code outside the code
Inheritance:
-----------------
-features from another class is referred as child or derived
or sub class
-features obtained is called parent or super class
-Reusability is the main use of it.
-ex:human generation
-"extends" keyword in for Inheritance
Polymorphism:
-------------------
-ability to appear many form(ex: multi personality
disorder)
-poly=many, morphism= ability to take forms.
-it is 2 types
Compile- Time polymorphism. It can be achieved through a
concept called Method Overloading.
--------------------------------------------
------------------------------
Run-Time Polymorphism. It can be achieved through a
concept called Method Overriding.
-------------------------------------
---------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
------
Member Variables / properties / Attributes
Member functions
Farm
getArea() return 1;
length
width
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-----
template{
class Student{
int no;
String name;
int age;
}
}
Static vs non-Static
=================
Static : ---> No instance dependency
directly accessed using class
non-Static :--> Instance dependency
can only be accessed using objects
When or Why to write static methods?
For utility methods
Arrays
[Link]()
[Link]()
[Link]()
Arrays.fill()
Arrays..3
Overloaded methods
Polymorphism
In java you can can write methods
with same name and different signatures
Methods overloading can be performed in 2 ways
1. By changing the number of parameters
2. By changing the type of parameters
Method overloading cannot be performed by changing the
return type
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
----
Generic Method Syntax:
=====================
<T>return_ type method_name (T parameters){
//Do Stuff
}
T ---> type of any datatype in this T place anything give any
thing like Type this called Generic Method Syntax.
Special Method called as constructor in Java
-----------------------------------------------------------------
1. Constructor is a special method in java,
which is used to construct an object of a class.
Constructing means assigning values to instance variables.
2. Constructors will allow us to send data while creating an
instance of a class.
3. Constructors will be invoke / called upon creation of each
instance
[Link] are 2 different types of constructors in Java
i) no-arg constructor
ii) parameterized / parametric constructor
5. If no constructor is written in the class Java compiler will
always add a default constructor.
Rules for creating a constructor:-
--------------------------------------------
1. Constructor name should be same as class name
2. Constructor is a method , but it should not contain any
explicit return type
3. Constructor can be written with parameters or without.
4. Constructor without parameters is called as a default /
no-arg constructor
5. A constructor with parameters is called parameterized
constructors.
6. Constructors are always called upon every instance
creation.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
Access / Visibility Modifiers in java :
==============================
There are 3 visibility modifiers in java
public
private
protected
Visibility modifiers will decide the visibility/ access to a
field or a method or a class in java.
Visibility modifiers are used to perform encapsulation /
data hiding.
public
universal access
can be accessed within the class and within the package
and outside the package as well.
private
restricted access
can only be accessed with in the class
protected
restricted access
can only be accessed within the package and within the
sub/derived/child classes outside the package.
default
package - private access
can only be accessed within the current package.
==================================================
=============================
|| || || || outside
the || ||
||modifier / || within the || within the || package
but || outside the ||
||scope || class || package || within
|| package in all ||
|| || || ||
subclasses || class ||
==================================================
============================
public -------> Yes Yes Yes
Yes
private ------> Yes No No
No
protected -----> Yes Yes Yes
No
default -----> Yes Yes No
No
==================================================
=============================
setters
getter()
getters are methods which we can use to display the private
members to users.
"this" keyword in java:-
-------------------------------
1."this" refers to the current object in java.
[Link] use of this is to distinguish between formal
arguments and instance variables
[Link] keyword can also be used to perform constructor
chaining using existing constructor.
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-------
Inheritance in java
================
inheritance :
-----------------
1. inheritance is a mechanism in which the child class
obtain the attributes / behaviors of a parent class
2. inheritance is a parent -child relationship
3. basically inheritance in java allows us to build the new
classes upon existing classes thus by providing reusability
of code in an efficient way.
4. inheritance is also called as an Parent-child ,"IS-A"
relationship
[Link] commonly used words in inheritance are:
i) parent / super / base class.
ii) child / sub / derived class.
[Link] class is a class from which child classes are built.
7. Child class is a class which inherits from parent class.
[Link] Java inheritance can be achieved by extends keyword
through the following syntax
class B extends A
[Link] the above example
A is a Parent / Super / Base class whereas
B is a Child / Sub / Derived class.
class AdvancedCalculator extends SimpleCalculator
=============================================
SimpleCalculator --> Parent / Super / Base class
AdvancedCalculator -->Child / Sub / Derived class
1. Every member of the parent can be obtained by child
class except private and static members.
Types of inheritance:
==================
[Link] Inheritance :
A class is derived from another class .
Ex: class B extends A
2. Multi-Level Inheritance :
Grandparent - parent - child relationship.
Ex: class B extends A
class C extends B
[Link] Inheritance
4. Multiple Inheritance
[Link] Inheritance
==================================================
==================================================
Method Overriding in java:
1. Let's say a class X is having a method printSomething()
2. Let's also say a class Y extends X and has a method with
the same signature printSomething() , then it's called
method Overriding .
3. Method overriding performs polymorphism . Same
method behaves differently in each class.
4. In overriding
the method in parent class is called as Overridden
method
the method in child class is called as Overriding method
==================================================
=================================================
final keyword restricts stuff
final class ---> The class can't be sub-class
Family Planning
final method --> The method can't be over-ridden
final variable --> Making this variable as a constant
Once the data is set. You can't change it.
_____________________
MySql --> Installer
Java Concepts
1. Data type and Variables
2. Scope of Variables
3. Operators
4. Arrays -> Arrays Class
5. Java Collection Framework -> Dynamic Arrays (ArrayList)
6. Multi-Dimensional Arrays, Variable Sized Arrays
7. Strings --> String class and StringBuider
8. Object Oriented Programming
9. classes and objects, members of a class, static vs.
non-static
10. Method overloading
11. constructors and constructor overloading and this
keyword
12. Access modifiers --> public, private, protected, default
13. Inheritance and types
14. Method Overriding and super keyword
15. Dynamic Method Dispatching
Java Operators
Operators are used to perform operations on variables and
values.
In the example below, we use the + operator to add together
two values:
ExampleGet your own Java Server
int x = 100 + 50;
Abstraction:
==========
Providing essential details without including
syntax:
---------
abstract class class_name
{
//abstract methods
//non abstract methods
// constructors
}
abstract method:
-----------------------
a method without body is called abstract method
syntax:
---------
abstract return_type methodName():
ActionEvent ---> class in [Link]
button click
selecting a checkbox
unselecting a checkbox
selecting an
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
----
Inheritance
extends
Polymorphism
method overloading / overriding
Abstrtion
abstract methods
method without any boby
method declaration
Syntax:
abstract returntype mrthod_name(parameters);
abstract classes
1. is class which contains at least one abstact method
2.
ActionListener --> Interface
1. 100% percent abstraction
abstract methods
2. Must be implemented
class X implemented
ArrayList
getArrayListElement()
Vector
getVectorElement()
LinkedList
getLinkedListElement()
AbstractList --> Abstract class
get()
interfaces
MouseListener --> Interface
5 abstract methods
1. MousePressed()
[Link]()
[Link]()
[Link]()
5. MouseClicked()
MouseEvent
1. MousePressed
[Link]
[Link]
[Link]
5. MouseClicked
Abstract class
1. A class is called abstract
Frame
Lable ComboBOx Button
red submit
green
black
blue
JTextArea
JLable
JButton
JFrame
JRadioButton
JComboBox
Event-->ActionEvent
[Link];
[Link];
package:
-----------
uil
lang
swing
awt
[Link]
User defined
Error Handling
Error:
Syntactical error
[Link] semi colon
[Link] braces or double quotes
[Link]("Hello);
printf()
Logical Error
#include<stdio.h>
int main()
{
int a = 10 , b=20;
printf("%d",a+b);
}
Runtime Error/Exception
[Link]
Exception Handling
Give a way to handle the exceetion so that the rest of run
normally.
Excetion Handling in Java involveds these keywords
try,catch,finally,throw,throws
ArithmeticException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
InputMismatchException
NullPointerException
try:
Under
Sytax:
try {
//block of code
}
catch:
cath block is used to handle the exception raised bytry
block.
Syntax:
catch(ExceptionName var) {
//BLOCK OF CODE
}
super class
Exception is the Super Class
It can handle any type of exception
throws:
You can force the user who is using your method to
implement Excetion Handling method.
Syntax:
return_type methodName() throws Exception {
//method boby
}
Your own Exception
Exception by a fly --> throw keyword
Syntax:
class YourExceptionName extends Exception {
public YourExceptionName() {};
public YourExceptionName() {
}
TooYoungExcption