1 Java My Typed Notes
1 Java My Typed Notes
JDK - java development kit , it is collection of tools used for developing java application.
JVM - java virtual machine ,jvm enables to run java code at any O/S so it make java platform-
independent. Jvm executes compiled java bytecode
String[] args :
String [] args allows java program to accept input from the user when it run.
String[] args and string args[] both same.
String[] : is a array of string.
args : is a name of aaray. You can change the name but args is standard.
Literal in java :
A constant value which can be assigned to variable is called as a literal.
Keywords :
Words which are reserved and have a special meaning. E.g - super,final,int
etc.
Comments :
// -> single line comment
/* comment */ -> multi line comment
Reading data form user/keyboard
for that we need tyo cerate a object of Scanner class in java.
Scanner s = new Scanner(system.in)
Method Description
Opearteors :
String
String is sequence of caharcetr.
1. By string literal
2. By new keyword
1) String Literal
. String s="welcome";
2) By new keyword
. String s1="Welcome";
. String s2="Welcome";//It doesn't create a new instance
String methods :
String Name = “harry”
Conditional statement
They are decision making statemnt , whrn we have two or more choices amd select one of those then
we use control stsemnt.
. If
. If-else
. If-else-if
if (condition1) {
else if (condition2) {
else {
switch
int day = 4;switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;}
Loops
While
Do-while
For
Array
Array is collevtion of similar data type.
Declartion :
Int [] marks = new int[5]; ->declartion + memory allocatrion
Int marks = {12,3456,5,657,56}; -> declartion + initiliazation
Array length -> array_name.length;
Displaying array:
For(int i=0; i<marks.length ; I++){
Sout(marks[I]);
}
For-each array
For(int i : marks){
Sout(i);
}
2D Array
int [][]flats = new int[2][3];
3D array
String [][][] arr = new String[2][3][4];
import java.util.Scanner;
Types of Method
There are two types of methods in Java:
o Predefined Method - standard library method or built-in method. All predefined function are
static so we don’t needd to create the object for calling that.we can directly e.g. length(),
equals(), sqrt(),
o User-defined Method - defined by user
Calling a method :
A method is can be called by creating the object of the class in which the method is
exist. Then by syntex-> object_name.function_name();
Or we can call the mthod directly without creating object if it static method.
import java.util.Scanner;
Obj1.FindEvenOdd(num);
}
}
Static keyword
static keyword is a non-access
modifier that can be applied to variables,
methods, blocks, and nested classes.
class MyClass {
Static Variables:
static int count = 0; // Static variable
Belong to the class, not to any instance of the class. Int count2 =1;
Shared by all instances of the class.
Only one copy exists in memory. }
Can be accessed directly using the class name.
public class Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
Susyem.out.println(obj1.count2);//output=1
System.out.println(MyClass.count); // Output: 2
} class
MyClass {
} static void displayMessage() {
System.out.println("Hello from static
Static Methods: method!");
}
Belong to the class, not to any instance of the class. }
Can be called directly using the class name.
Cannot access non-static variables or methods directly. public class Main {
public static void main(String[] args) {
MyClass.displayMessage(); // Output: Hello
from static method!
}
}
Static Blocks:
class MyClass {
Executed only once when the class is loaded into memory. static int x;
Used for initializing static variables. static {
x = 10;
}
}
Method overloading
Also, known as compile-time polymorphism
two or more method can have same name but different parameters.
Note : method overloading cannot be performed by cahnging the return type of methods.
Variable Argument
A function with varargs can be created in java using the follwing syntax :
Uses : you can called a function with zero or more argument .
public class VarArgs {
1.Class : a class is buleprint for creating object . Collection of objects is called class.
It is a user-defined data type, which holds its own data members and member functions,
2. object : An object is an instance of a class. When you create an object, you are allocating
memory to store its attributes and methods.
For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.
E. g
// Java Program to demonstrate Use of Class and Objects
// Class Declared
public class GFG {
// Properties Declared
static String Employee_name;
static float Employee_salary;
// Methods Declared
static void set(String n, float p) {
Employee_name = n;
Employee_salary = p;
}
// Main Method
public static void main(String args[]) {
GFG.set("Rathod Avinash", 10000.0f);
GFG.get();
}
}
Oops terminoly :
1. Abstarction : hiding internal detials and showing only essential details. E.g we use car without knowing interal
machinsim.
Note: In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
// Setter methods
public void set_id(int empid) {
this.empid = empid;
}
// Getter methods
public int get_id() {
return empid;
}
class).The derived
public class Geeks { class inherits features from the base class and can have additional features of its own also.
class parent{
protected int a=20;
public int b=2;
private int c=34;
parent(){
System.out.println("parent constructor");
}
void fun(){
System.out.println("parent class");
}
}
}
public class inhertitance {
public static void main(String[] args) {
child obj1 = new child();
}
}
Oredr of execution of Constructor in inheritance :
1. Parent ->2. child ->3. grandchild
Types of inheritance :
Note- multiple inheritance not support in java ,we can achiwve it by interface
Imagine:
Class A has a method called calculate().
Class B also has a method called calculate().
Class C inherits from both A and B.
Problem:
If Class C tries to use calculate(), which one should it use? A's version or B's? This creates ambiguity
and confusion.
Solution:
Java uses interfaces to achieve similar functionality. A class can implement multiple interfaces, each
defining a set of methods the class must implement. This avoids the ambiguity of multiple inheritance while
allowing for flexible code reuse.
4. Polymorphism- The word “polymorphism” means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism is a person who at the same time can have different characteristics. A man
at the same time is a father, a husband, and an employee.
Types of Polymorphism
Polymorphism in Java is mainly of 2 types as mentioned below:
1. Method Overloading
2. Method Overriding
// Method Declared
public void func(){
System.out.println("Parent Method func");
}
// Method Overloading
public void func(int a){
System.out.println("Parent Method func " + a);
}
}
// Method Overriding
@Override
public void func(int a){
System.out.println("Child Method " + a);
}
}
// Main Method
public class Main {
public static void main(String args[]){
Parent obj1 = new Parent();
obj1.func();
obj1.func(5);
Output
Parent Method func
Parent Method func 5
Child Method 4
Access modifires
Getters / Setters
Getters - return thr value [accessors]
Setters - sets/updates value [mutators]
For example :
Public class emloyee{
private int id;
Private String name;
Public String getNmae(){
return name;
}
Public void setname(String s){
this.name = s;
}
}
Constructor
Constructor are member function used to initialize an object when we create it. It has the same
name as the class and does not have a return type (not even void).
RULE to define constructor -
1. Constructor name and class name must be same.
2. Constructor are must be declared as public.
Note: - constructor can be overload.
----------------------------------------------------------------
public class Car {
String make;
String model;
int year;
// Default constructor
public Car() {
make = "Unknown";
model = "Unknown";
year = 0;
}
// Parameterized constructor
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
----------------------------------------------------------------------------
Constructor overloading
*Constructor overlaoding is compile time polymorphism
Similar to Java method overloading, we can also create two or more constructors with different parameters. This
is called constructor overloading.
->if we want to constructor with parameter of parent class from child class then use super keyword
class Main {
String language;
obj1.getName();
obj2.getName();
}
}
Super Keyword
used to call the imidiate parent class method or variable is known as a super keyword.
super() Constructor
The super() is mainly used for invoking imidiate parent class member functions and constructors.
This Keyword
It is a reserved keyword in Java that is used to refer to the current class object. It is a reference variable through
which the method is called.
o We can use it to invoke the current class method (implicitly) and variables
Example :
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void makeSound() {
System.out.println("Generic animal sound");
}
}
@Override
void makeSound() {
System.out.println("Woof!");
}
void printName() {
System.out.println("Name: " + this.name); // Refers to the current object's name
}
}
Upcasting : It is a technique in which a superclass reference variable refers to the object of the
subclass.
Example :
class Animal{}
class Dog extends Animal{}
Example:
class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
public void on(){
System.out.println("Turning on Phone...");
}
}
class SmartPhone extends Phone{
public void music(){
System.out.println("Playing music...");
}
public void on(){
System.out.println("Turning on SmartPhone...");
}
}
obj.showTime();
obj.on();
// obj.music(); Not Allowed
}}
Output :
Time is 8 am
Turning on SmartPhone...
Abstract class
It may have both abstract and non-abstract methods(methods with bodies).
abstract class is declared with the abstract keyword.
An abstract is a Java modifier applicable for classes and methods in Java but not for
Variables
We can have an abstract class without any abstract method.
We can define static methods in an abstract class
There can be a final method in abstract class but any abstract method in class(abstract
class) can not be declared as final or in simpler terms final method can not be abstract itself
as it will yield an error: “Illegal combination of modifiers: abstract and final”
If a class contains at least one abstract method then compulsory should declare a class
as abstract
If a child class extends parent class then child class must implemnt all abstarct method of
parent class , If the Child class is unable to provide implementation to all abstract methods
of the Parent class then we should declare that Child class as abstract so that the next
level Child class should provide implementation to the remaining abstract method
it is not possible to create an object of the Animal class:
way to achieve abstraction in Java,
A class said to be complete abstatc class if all the methods in it are abstrct.
// Abstract class
abstract class Sunstar {
abstract void printInfo();
}
// Base class
class Base {
public static void main(String args[]) {
Sunstar s = new Employee();
s.printInfo();
}
}
Output
avinash
21
222.2
Exammple 2 ;
void Learn(){
System.out.println("Preparing Right Now!");
}
}
class GFG {
public static void main(String[] args) {
Subject x=new IT();
x.syllabus();
x.Learn();
}
}
Output
Learning Subject
C , Java , C++
Preparing Right Now!
Abstract method
A Method that is declared without any implmentation is called abstarc method.
It define using abstract keyword.
If a class contains an abstract method it needs to be abstract and vice versa is not true.
way to achieve abstraction in Java
If a non-abstract class extends an abstract class, then the class must implement all the
abstract methods of the abstract class else the concrete class has to be declared as abstract
as well.
Interface
an interface in Java provides 100% abstraction
Interface methods do not have a body - the body is provided by the "implement" class
On implementation of an interface, you must override all of its methods
*Interface methods are by default abstract and public
*Interface attributes are by default public, static and final
An interface cannot contain a constructor
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be
achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple
interfaces, separate them with a comma (see example below).
Class Interface
In class, you can instantiate variables and In an interface, you must initialize variables as
create an object. they are final but you can’t create an object.
A class can contain concrete (with The interface cannot contain concrete (with
implementation) methods implementation) methods.
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
Implemnt an interfaece :
So, the question arises why use interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in the
interface are final, public, and static.
Exapmle of inteface :
interface Animal {
System.out.println("Zzz");
}}
class Main {
public static void main(String[] args) {
myPig.animalSound();
myPig.sleep();
}}
Multiple Interfaces
interface FirstInterface {
interface SecondInterface {
//multiple interface
System.out.println("Some text..");
class Main {
myObj.myMethod();
myObj.myOtherMethod();
1. An abstract class can contain both abstract and Interface contains only abstract
non-abstract methods. methods.
2. An abstract class can have all four; static, non- Only final and static variables are
static and final, non-final variables. used.
3. To declare abstract class abstract keywords are The interface can be declared with
used. the interface keyword.
6. It has class members like private and protected, It has class members public by
etc. default.
Default methods
Imporant concept : Before Java 8, interfaces could only have abstract methods. So ,when we
implement a interface in class then that class must provide implementation of all of these
methodsof inteface. So, if a new method is to be added in an interface, then its implementation
code has to be provided in the class implementing the same interface. To overcome this issue,
Java 8 has introduced the concept of default methods which allow the interfaces to have
methods with implementation(with body) which cannot affect the classes that implement the
interface.
. interface Sayable{
. // Default method
.
. default void say(){
. System.out.println("Hello, this is default method");
. }
.
. // Abstract method
. void sayMore(String msg);
. }
.
. public class DefaultMethods implements Sayable{
.
. public void sayMore(String msg){ // implementing abstract method
. System.out.println(msg);
. }
.
. public static void main(String[] args) {
. DefaultMethods dm = new DefaultMethods();
. dm.say(); // calling default method
. dm.sayMore("Work is worship"); // calling abstract method
.
. }
.
. }
Output :
Hello, this is default method
Work is worship
Inheritance in interfaces
Interface can extend another inerface using extends keyword.
interface animal {
void m1();
}
interface pig exends animal {
void m2();
}
Package
Package in java is used to group related classes .
packages help organize your Java code and prevent naming conflicts.
Packages can be considered as data encapsulation (or data-hiding).
Example : college.staff.cse ;
For example if a package name is college.staff.cse, then there are three
directories, college, staff and cse such that cse is present in staff and staff is present
inside college. So , Package names and directory structure are closely related.
Example :
import java.util.*;
util is a subpackage created inside java package.
Threading
How to Create Threads in Java?
We can create Threads in java using two ways, namely :
1. Extending Thread Class
2. Implementing a Runnable interface
Output
Thread Started Running...
}
public class Geeks{
public static void main(String[] args) {
// Running Thread
g1.start(); // fire the gun
}
}
@Override
public void run() {
for(int i=0;i<10;i++)
System.out.println("thread is runing");
}
}
gun1.start();
System.out.println("thread id is : "+gun1.getId() + " and name :
"+gun1.getName() );
}
}
Multithreading
}
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("java");
try {
Thread.sleep(400); //pause the execution of the current thread for specify
time
} catch (InterruptedException e) {
System.out.println("InterruptedException occur");
}
}
}
}
class thread_methods_2 extends Thread{
@Override
public void run() {
}
}
t1.start();
System.out.println(t1.getState());
/* try{
t1.join(); //Waits for this thread to die then other thread will run
} catch (Exception e) {
System.out.println(e);
}
*/
t2.start();
}
}
Set priority
@Override
public void run(){
System.out.println("hellow " +this.getName());
}
}
t4.setPriority(Thread.MAX_PRIORITY);
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MIN_PRIORITY);
t3.setPriority(Thread.NORM_PRIORITY);
t5.setPriority(Thread.MIN_PRIORITY);
System.out.println(t4.getPriority());
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
Eception handling
Exception handling
An exception is occurs during the execution of a program that disrupts the normal flow of instructions.
Exceptions are typically used to indicate an error has occurred and to transfer control to a specific location in
the code where the error can be handled.
The main benefit of using exceptions is that it allows you to handle by separate code the error handling
from the normal code, making it more readable and maintainable. The exception-handling code can be
kept separate from the rest of the code and can be reused easily across the program.
Keyw Description
ord
The "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be
try
followed by either catch or finally.
The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by
catch
finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.
The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It
throws
is always used with method signature.
try{
int c=a/b;
} catch (Exception e) {
System.out.println("can't be divide");
System.out.println(e);
}
System.out.println("end of program");
}
}
System.out.print("enter the number you want to divide the value with : ");
int num = st.nextInt();
try{
Custom exception :
class InvalidAgeException extends Exception {
// A Class that represents user-defined exception public InvalidAgeException(String m) {
class MyException extends Exception { super(m); //message
public MyException(String m) { }
super(m); }
}
} // Using the Custom Exception
public class Geeks {
// A Class that uses the above MyException public static void validate(int age) throws InvalidAgeException {
public class setText { if (age < 18) {
public static void main(String args[]) { throw new InvalidAgeException("Age must be 18 or
try { above.");
// Throw an object of user-defined exception }
throw new MyException("This is a custom System.out.println("Valid age: " + age);
exception"); }
}
catch (MyException ex) { public static void main(String[] args) {
System.out.println("Caught"); // Catch and print try {
message validate(12);
System.out.println(ex.getMessage()); } catch (InvalidAgeException e) {
} System.out.println("Caught Exception: " + e.getMessage());
} }
// we can write our cusstom exception using exception class in java.
@Override
public String getMessage() // print the exception message
{
return " getMessage() invoke" ;
// return super.getMessage()+" getMessage() invoke";
}
}
public class ch_83_custom_exception {
public static void main(String[] args) {
try {
throw new myexception();
}
catch (Exception e){
System.out.println(e.getMessage());
System.out.println(e.toString());
System.out.println(e);
}
}
}
Throw keyword :
import java.io.*;
public class ch_83_throw_keyword {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Throws
The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an
exception. It is always used with method signature.
@Override
public String getMessage() {
return "radius canot be negative ";
}
}
System.out.println("program is finished..");
}
}
Nested exception :
import java.util.Scanner;
while(flag){
System.out.print("enter the index for array : ");
int idx = st.nextInt();
try {
try {
System.out.println(marks[idx]);
flag=false;
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("Sorry this index does not exit");
System.out.println("exception level 2 ");
}
}catch (Exception e){
System.out.println();
}
}
}