Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views34 pages

1 Java My Typed Notes

The document provides an overview of Java programming concepts, including its object-oriented nature, data types, methods, and control structures. It explains key components such as JDK, JRE, and JVM, along with syntax for user input, string manipulation, and conditional statements. Additionally, it covers object-oriented programming principles like encapsulation, inheritance, and polymorphism, along with examples of method overloading and the use of static keywords.

Uploaded by

Ritx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views34 pages

1 Java My Typed Notes

The document provides an overview of Java programming concepts, including its object-oriented nature, data types, methods, and control structures. It explains key components such as JDK, JRE, and JVM, along with syntax for user input, string manipulation, and conditional statements. Additionally, it covers object-oriented programming principles like encapsulation, inheritance, and polymorphism, along with examples of method overloading and the use of static keywords.

Uploaded by

Ritx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

JAVA

Java is fully object orientd language


Java is hybrid language means it is both compled and interpreted.

JDK - java development kit , it is collection of tools used for developing java application.

JRE - java runtime environment , helps in executing programs of java.

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

Structure of java program -

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.

Java data type

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)

(read from keyboard)

Int a = s.nextInt(); // to read inetger

Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

Q. How to input a char type data-


R. Char b1 = s.next().charAt(1);

Check type of input :


boolean b1 = s.hasNextInt(); // checks inetger or not
Boolean b2 = s.hasnextDouble()

Opearteors :

Different way to print in java :

System.out.println(); // prints new line in end


System.out.print(); // no line in end
System.out.printf(); // e.g-> System.out.println(“%d”,x);

String
String is sequence of caharcetr.

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal

. String s="welcome";

2) By new keyword

. String s=new String("Welcome");

String constant pool :


String objects are stored in a special memory area known as the "string constant pool".
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string already exists in
the pool, a reference to the pooled instance is returned. If the string doesn't exist in the pool, a new string instance
is created and placed in the pool. For example:

. String s1="Welcome";
. String s2="Welcome";//It doesn't create a new instance

Why java string are immutable :


string immutable means their value cannot be chaned once they are created, Bcz they shaerd content in
single pool to minimize creating a copy of same value.

String methods :
String Name = “harry”

Name .length() : returns length =5;


Name.toLowerCase() : return string which all character in lower case .
Name.toUpperCase() : return string which all charcetr in upper case
Name.trim() : Removes whitespace from both ends of a string start and end.
Name.substring(int start) : return string fom stsrt to end of out string . e.g name.string(3) -> output = ry
Name.substring(int start,int end) : e.g name.substring(1,3) -> output =arr
Name.replace(‘r’,’p’) : return new string with relace r with p instring
Name.chatAt(2) : return characetr at 2 index in string
Name.indexOf(“ar”) : return the index of “ar”(return first occrnace).
Name.LastIndexOf(“r”) : return the last index of given string . 3 in this case.
Name.equals(“harry”) : return ture if the given string is equal to “Harry” (case -sensitve)
Name.euqlsIgnorecase(“harry”) : return ture if two string are qual ( case in-senstive )
For more methods go to google :)

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) {

// block of code to be executed if condition1 is true}

else if (condition2) {

// block of code to be executed if the condition1 is false and condition2 is


true}

else {

// block of code to be executed if the condition1 is false and condition2 is


false}

Using Ternary opeartor:

(condition) ? expressionTrue : expressionFalse;

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;

public class array {

public static void main(String[] args) {


Scanner st = new Scanner(System.in);

int [] arr= new int[5];

for(int i=0; i < arr.length;i++)


arr[i]=st.nextInt();

for (int i :arr)


System.out.print(i+" ");

int[] arr2 = {23,56,78,89,9};

char[] arr3 = {'r','t','o','r','q'};


for(char i : arr3){
System.out.println(i);
}
}
}
Function/methods
methods follow DRY principal , do not repaet your self.

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;

. public class EvenOdd {

//user defined method


public void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
.

public static void main (String args[]) {


//create object
EvenOdd obj1 = new EvenOdd();

//creating Scanner class object


Scanner scan=new Scanner(System.in);

System.out.print("Enter the number: ");


int num=scan.nextInt();

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.

public class method_overloading {


static void fun1(){
System.out.println("fdfd");
}
static void fun1(int x){
System.out.println(x);
}
static void fun1(int x , int y){
System.out.println(x+y);
}

public static void main(String[] args) {


fun1();
fun1(34);
fun1(2,5);
}

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 {

//it take zero or more argument


static void var_args_func(int...arr){
int sum=0;
for(int i: arr){
sum+=i;
}
OOP
Object oriented programing is solving a problem y creating object is
called object orinted programing.
Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism, etc.

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;
}

static void get() {


System.out.println("Employee name is: " +Employee_name );
System.out.println("Employee CTC is: " + Employee_salary);
}

// Main Method
public static void main(String args[]) {
GFG.set("Rathod Avinash", 10000.0f);
GFG.get();
}
}

How to modal a problem :


Class - employee
Attribute/data member - name ,age ,salary
Methods - getsalary() , incerment();

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.

Below is the implementation of abstraction using Abstract class:


2
// abstract class
abstract class GFG {
// abstract methods declaration
abstract void add();
abstract void mul();
abstract void div();
}

2. Encapsulation : It is defined as the wrapping up various component together in a single unit.


In java encapsulation means sensitive data can be hidden from users.
E.g - laptop is single entity with wifi +speker box + storage in a single unit.
\\\\
// Encapsulation using private modifier

// Employee class contains private data


class Employee {

private int empid;


private String ename;

// Setter methods
public void set_id(int empid) {
this.empid = empid;
}

public void set_name(String ename)


{
this.ename = ename;
}

// Getter methods
public int get_id() {
return empid;
}

public String get_name() {


return ename;
}
3.} Inheritance : Inheritance allows us to create a new class (derived class) from an existing class (base

class).The derived
public class Geeks { class inherits features from the base class and can have additional features of its own also.

public static void main(String args[])


**Implements
{ DRY.
Employee e = new Employee();
 Superclass:
e.set_id(78); The class whose features are inherited is known as superclass (also known as
e.set_name("John");
base or parent class).
 Subclass: The class
System.out.println("Employee id: " +that inherits the other class is known as subclass (also known as derived
e.get_id());
or extended or child
System.out.println("Employee Name:class). The subclass can add its own fields and methods in addition to the
" + e.get_name());

}superclass fields and methods.


}

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");
}
}

class child extends parent{


child(){
this.a=23; // update varble for child class
super.b=5; // update parent class objcet
System.out.println("child constructor");
System.out.println(a);
System.out.println(b);

}
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

parent Constructor during constructor overlaoding-


**Constructor overlaoding is compile time polymorphism
When there are multiple constructor in the parent class then the deafault construcot is called from the
child class.
->if we want to call constructor with parameter of parent class from child class then use super
keyword.
Super(a,b); // class consstror of parent class which takes 2 argument.

Types of inheritance :

Note- multiple inheritance not support in java ,we can achiwve it by interface

Q- Why multiple inheritance not support in java ?

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

1. Method Overloading: done at pre pages….


2. Method Overriding: Also, known as run-time polymorphism, is the concept of Polymorphism
where method in the child class has the same name, return-type and parameters as in parent class.
The child class provides the implementation in the method already written.
**we cam't override static,final methods
Note : use @override anotation when you override for better understanding.
// Java Program to Demonstrate Method Overloading and Overriding
class Parent {

// 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);
}
}

class Child extends Parent {

// 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);

Child obj2 = new Child();


obj2.func(4);
}
}

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;
}

public static void main(String[] args) {


Car car1 = new Car(); // Calls default constructor
Car car2 = new Car("Toyota", "EIOS", 2023); // Calls parameterized constructor
}
}

----------------------------------------------------------------------------

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;

// constructor with no parameter


Main() {
this.language = "Java";
}

// constructor with a single parameter


Main(String language) {
this.language = language;
}
public void getName() {
System.out.println("Programming Language: " + this.language);
}

public static void main(String[] args) {

// call constructor with no parameter


Main obj1 = new Main();

// call constructor with a single parameter


Main obj2 = new Main("Python");

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

this() Constructor : This() is used to call constructor of the same class.

Example :

class Animal {
String name;

Animal(String name) {
this.name = name;
}

void makeSound() {
System.out.println("Generic animal sound");
}
}

class Dog extends Animal {


Dog(String name) {
super(name); // Calls the constructor of the parent class (Animal)
}

@Override
void makeSound() {
System.out.println("Woof!");
}

void printName() {
System.out.println("Name: " + this.name); // Refers to the current object's name
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.makeSound(); // Prints "Woof!"
dog.printName(); // Prints "Name: Buddy"
}
}.

Dynamic Method Dispatch

 Dynamic method dispatch is also known as run time polymorphism.


 It is the process through which a call to an overridden method is resolved at runtime.
 This technique is used to resolve a call to an overridden method at runtime rather than compile
time.
 To properly understand Dynamic method dispatch in Java, it is important to understand the concept
of upcasting because dynamic method dispatch is based on upcasting.

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{}

//remember tip => super_class obj =new sub_classs


Animal a=new Dog();// upcasting -> //created an object of the Dog() class by taking the reference of
the Animal() class.

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...");
}
}

public class CWH {


public static void main(String[] args) {
Phone obj = new SmartPhone(); // Yes it is allowed
// SmartPhone obj2 = new Phone(); // Not allowed

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.

Elements abstract class can have


 data member
 abstract method
 method body (non-abstract method)
 constructor
 main() method.

// Abstract class
abstract class Sunstar {
abstract void printInfo();
}

class Employee extends Sunstar {


void printInfo(){
String name = "avinash";
int age = 21;
float salary = 222.2F;
System.out.println(name);
System.out.println(age);
System.out.println(salary);
}
}

// Base class
class Base {
public static void main(String args[]) {
Sunstar s = new Employee();
s.printInfo();
}
}
Output
avinash
21
222.2

Exammple 2 ;

// Java Program to implement Abstract Class


// having constructor, data member, and methods
import java.io.*;

abstract class Subject {


Subject() {
System.out.println("Learning Subject");
}

abstract void syllabus();

void Learn(){
System.out.println("Preparing Right Now!");
}
}

class IT extends Subject {


void syllabus(){
System.out.println("C , Java , C++");
}
}

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.

Abstarc methods are use in creating blueprint of classes and interface.


Syntax : abstract void m1();

Interface
an interface in Java provides 100% abstraction

 an interface could only have abstract methods (methods without a body)


 To implement an interface, we use the keyword implements
 Java Interface also represents the IS-A relationship.

Like abstract classes, interfaces cannot be used to create objects

 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

Why And When To Use Interfaces?


1) To achieve security - hide certain details and only show the important details of an object (interface).

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.

The access specifiers used with classes are


In Interface only one specifier is used- Public.
private, protected, and public.
Syntax for Java Interfaces

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 {

// public, static and final

Public int x = 20;

// public and abstarct

public void animalSound();

public void sleep();

class Pig implements Animal {

public void animalSound() {

System.out.println("The pig says: wee wee");

public void sleep() {

// The body of sleep() is provided here

System.out.println("Zzz");

}}

class Main {
public static void main(String[] args) {

Pig myPig = new Pig(); // Create a Pig object

myPig.animalSound();

myPig.sleep();

}}

Multiple Interfaces

interface FirstInterface {

public void myMethod();

interface SecondInterface {

public void myOtherMethod();

//multiple interface

class DemoClass implements FirstInterface, SecondInterface {

public void myMethod() {

System.out.println("Some text..");

public void myOtherMethod() {

System.out.println("Some other text...");

class Main {

public static void main(String[] args) {

DemoClass myObj = new DemoClass();

myObj.myMethod();

myObj.myOtherMethod();

Difference between Abstract Class and Interface in Java


S.No Abstract Class Interface
.

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.

4. It supports multiple inheritance. It does not support multiple


inheritance.

5. The keyword ‘extend’ is used to extend an The keyword implement is used to


abstract class implement the interface.

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.

Consider following two statements :


// import the Vector class from util package.
import java.util.vector;

// import all the classes from util package


import java.util.*;

Creating our first package:

package codewith_me; package codewith_me.package;


public class ClassOne {
public void methodClassOne() public class ClassTwo {
{ public void methodClassTwo()
System.out.println("Hello there its ClassOne");
}
{
} System.out.println("Hello there i am
ClassTwo");
}
}
Note : to understand package go to code with harry yt video

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

1. Extending Thread Class

class MyThread extends Thread {


// initiated run method for Thread
public void run() {
String str = "Thread Started Running...";
System.out.println(str);
}
}

public class Geeks{


public static void main(String args[]){
MyThread t1 = new MyThread();
t1.start();
}
}

Output
Thread Started Running...

2. Implementing a Runnable interface


import java.util.*;

class MyThread implements Runnable {


// Method to start Thread
public void run(){
String str = "Thread is Running Successfully";
System.out.println(str);
}

}
public class Geeks{
public static void main(String[] args) {

MyThread bullet1 = new MyThread(); //bullet ready

// initializing Thread Object


Thread gun1 = new Thread(bullet1); // load bullet in gun

// Running Thread
g1.start(); // fire the gun
}
}

Commonly used construcion of thread class


Java provides several constructors for the Thread class:

Commonly Used Constructors:


 Thread(): Creates a new thread with no specified name or runnable target.
 Thread(String name): Creates a new thread with the specified name.
 Thread(Runnable target): Creates a new thread that executes the specified Runnable object.
 Thread(Runnable target, String name): Creates a new thread that executes the
specified Runnable object and has the specified name.

Demonstrate -> Thread(String name) ,Thread(Runnable target, String name):

class make_thread extends Thread {


// Tread class constructor -> Thread(String s)
public make_thread(String name){
super(name);
}

@Override
public void run() {
for(int i=0;i<10;i++)
System.out.println("thread is runing");
}
}

// Tread class constructor


class make_thread2 implements Runnable{
@Override
public void run() {
for(int i=0;i<10;i++)
System.out.println("thread is runing by runnable interfacae");
}
}

public class ch_73_thread_constructor {


public static void main(String[] args) {
make_thread t1 = new make_thread("ritesh");
t1.start();
System.out.println("the id : " +t1.getId()+ " and Thread name is : "+t1.getName());

/// thread(runnable r , String s)

make_thread2 bullet1 = new make_thread2();


Thread gun1 = new Thread(bullet1,"fod dega");

gun1.start();
System.out.println("thread id is : "+gun1.getId() + " and name :
"+gun1.getName() );
}
}

Thread classs methods


start() It is used to start the execution of the thread.

run() It is used to perform action for a thread.

sleep() It sleeps a thread for the specified amount of time.

join() It waits for a thread to die.

getPriority() It returns the priority of the thread.

setPriority() It changes the priority of the thread.

It returns the name of the thread.


getName()

isAlive() It tests if the thread is alive.

getId() It returns the id of the thread.

It is used to stop the thread.


stop()

getState() It is used to return the state of the thread.

Multithreading

class demo_thread extends Thread{


@Override
public void run() {
for(int i=1; i<=100;i++)
System.out.println("tread 1 is runing");
}
}
class demo_thread2 extends Thread{
@Override
public void run() {
for(int i=1;i<=100;i++)
System.out.println("tread 2 is runing");
}
}
public class ch_70_threading {

public static void main(String[] args) {


demo_thread t1 = new demo_thread();
demo_thread2 t2 = new demo_thread2();
t1.start();
t2.start();

}
}

Use thread mehods


class thread_methods_1 extends Thread {
public thread_methods_1(String name){
super(name);
}

@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() {

for(int i=0;i<1000 ;i++)


System.out.println("app devlopment");

}
}

public class ch_75_thread_methods {


public static void main(String[] args) {
thread_methods_1 t1 = new thread_methods_1("ghda");
thread_methods_2 t2 = new thread_methods_2();
System.out.println("thread name is : "+t1.getName());
System.out.println("Thread ID is : "+t1.getId());
System.out.println("thread state : "+t1.getState()); // Returns the state of this
thread
System.out.println(t1.isAlive()); //Tests if this thread is alive
t1.interrupted();

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

class thread_priority extends Thread {


public thread_priority(String name){
super(name);
}

@Override
public void run(){
System.out.println("hellow " +this.getName());
}
}

public class ch_74_thread_priority {


public static void main(String[] args) {

thread_priority t1 = new thread_priority("ramji");


thread_priority t2 = new thread_priority("hnumanji");
thread_priority t3 = new thread_priority("laxmanji");
thread_priority t4 = new thread_priority("bharatji (important )");
thread_priority t5 = new thread_priority("satrudhanji");

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);

//set priority by passing integer arguments


// t1.setPriority(2);
// t2.setPriority(5);
// t3.setPriority(8);

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.

E.g - IOexception, calssnot foundexception, divodeby zero exception.

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.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table describes each.

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.

throw The "throw" keyword is used to throw an exception.

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.

Example of exception handling :

public class ch_80_exception_jandling {


public static void main(String[] args) {
int a=500;
int b=0;

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");
}
}

Example for multiple/specific exception :


import java.io.IOException;
import java.util.Scanner;

public class ch_81_specific_exception {


public static void main(String[] args) {
int[] arr = new int[2];
arr[0]=23; arr[1]=435;

Scanner st = new Scanner(System.in);

System.out.print("enter index of array : ");


int indx=st.nextInt();

System.out.print("enter the number you want to divide the value with : ");
int num = st.nextInt();

try{

System.out.println("the value at aaray index that you entered is :


"+arr[indx]);
System.out.println("the array-value/number : "+arr[indx]/num );

}catch (ArrayIndexOutOfBoundsException e){


System.out.println("arrayIndexOutOfBound exception "+e);
} catch (ArithmeticException e) {
System.out.println("arithmetic exception "+e);
}
catch (Exception e){
System.out.println("other exception "+e );
}
finally{
System.out.println("final code---");
}
}
}

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.

class myexception extends Exception{


@Override
public String toString() // execute when sout(e) run
{
return " tostring() invoke ho gya ";
// return super.toString()+" tostring() invoke ho gya ";
}

@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.

class neagtive_radius_exception extends Exception{


@Override
public String toString() {
return "radius cannot be negative";
}

@Override
public String getMessage() {
return "radius canot be negative ";
}
}

public class ch_84_throws_keyword {


//throws keyword used to decalre an exception this gives an information to the programmer that there might be an exception ,so
better to be prepaerde with try catch bloack.

public static double area(int radius) throws neagtive_radius_exception{


if (radius<0){
throw new neagtive_radius_exception();
}
return Math.PI*radius*radius;
}

public static double divide(int a ,int b ) throws ArithmeticException{


return a/b;
}
public static void main(String[] args) {
try {

double area = area(-4);


System.out.println("area is : "+area);
}
catch(Exception e){
// System.out.println(e.getMessage());
System.out.println(e);
System.out.println("exception occur!");
}

System.out.println("program is finished..");
}
}

Nested exception :
import java.util.Scanner;

public class ch_82_nested_try_catch {


public static void main(String[] args) {
int[] marks = new int[3];
marks[0]=13;
marks[1]=34;
marks[2]=89;

Scanner st = new Scanner(System.in);


boolean flag =true;

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("excception level 1 ");


}

System.out.println();
}

}
}

You might also like