Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Core java notes, Exception, reference variables, String,

The document contains Java code examples for various applications including a Day Finder, Number Converter, and exception handling. It explains concepts like instance variables, constructors, exception handling, and string manipulation in Java. Additionally, it covers multithreading and the importance of handling exceptions to prevent program termination.

Uploaded by

namanr073
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Core java notes, Exception, reference variables, String,

The document contains Java code examples for various applications including a Day Finder, Number Converter, and exception handling. It explains concepts like instance variables, constructors, exception handling, and string manipulation in Java. Additionally, it covers multithreading and the importance of handling exceptions to prevent program termination.

Uploaded by

namanr073
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Day Finder:

import java.util.Scanner;

public class DayFinder


{
public static void main(String[] args)
{
String[] days=
{"Thursday","Friday","Saturday","Sunday","Monday","Tuesday","Wednesday
"};
Scanner sc=new Scanner(System.in);
System.out.print("Enter any date of current month:");
int date=sc.nextInt();
if(date<1 || date>31)
System.out.println("Invalid date");
else
{
int i=date%7;
System.out.println("Day is :"+days[i]);
}
}
}

Day Finder by month & Year


import java.util.Scanner;

public class DayFinder3


{
public static void main(String[] args)
// Day is finderin year by Month and day
{
String[] days=
{"Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday","Monday
"};
int[] nod={31,29,31,30,31,30,31,31,30,31,30};
Scanner sc=new Scanner(System.in);
System.out.print("Enter any month of current year:");
int month=sc.nextInt();
System.out.print("Enter any date of entered month:");
int date=sc.nextInt();
int total=0;
for(int i=0;i<month-1;i++)
{
total=total+nod[i];
}
total+=date;
int i=total%7;
System.out.println("Day is/was: "+days[i]);

}
}

Two digits Converter


import java.util.Scanner;

public class NumberConverter


//number coverter 2 digits only
{
static String[] x=
{"","one","two","three","four","five","six","seven","eight","nine","te
n","eleven","twelve","thirteen","fourteen","fifteen","sixteen","sevent
een","eighteen","nineteen"};
static String[] y= {"", "",
"twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"}
;
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number one to ninety-nine:");
int n=sc.nextInt();
if(n>=1 && n<=19)
{
System.out.print(x[n]+" ");
}
if(n>=20 && n<=99)
{
System.out.print(y[n/10]+" "+x[n%10]);
}
}
}

Number converter lengthy digit


import java.util.Scanner;

public class NumberConverter4


{
static String[] x=
{"","one","two","three","four","five","six","seven","eight","nine","te
n","eleven","twelve","thirteen","fourteen","fifteen","sixteen","sevent
een","eighteen","nineteen"};
static String[] y=
{"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","n
inety"};
static void convert(int n)
{
if(n>=1 && n<=19)
{
System.out.print(x[n]+" ");
}
if(n>=20 && n<=99)
{
System.out.print(y[n/10]+" "+x[n%10]+" ");
}
if(n>=100 && n<=999)
{
convert(n/100);
System.out.print("hundred ");
convert(n%100);
}
if(n>=1000 && n<=99999)
{
convert(n/1000);
System.out.print("thousand ");
convert(n%1000);
}
if(n>=100000 && n<=9999999)
{
convert(n/100000);
System.out.print("lakh ");
convert(n%100000);
}
if(n>=10000000 && n<=999999999)
{
convert(n/10000000);
System.out.print("crore ");
convert(n%10000000);
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number:");
int n=sc.nextInt();
convert(n);
}
}

05-march-2024
Iside class you will have to define
1. Instance Variables
2. Constructor
3. Getters and Setter
a. Instance Variables:- those variables that are declared/define
inside class without using static keyword are known as
instance variable.
Thses variables will be attribute of object and hold states of
object.
Since object is an instance of the class that’s why these
variables are known as instance variables.
Public class product{
// Declaring instance variables
Private int pid;
Private string name;
Private string brand;
Private int price;
}
These commands(command to create instance variable) are
executed each time object from that class will be created by
any program.
These variable will be initialize(assign value first time)
also
// default value will be 0
// Default value java int =0, int series(byte,int, short)
//float or double 0.0
//boolean : False
//char: Null character
// long :0
// float: 0.0
// char: null character (`/u0000`)
//non primitive:- null
//class

# New product();
Command to create from class product
Command to create object from Class:

New Class name();

Or new Classname(parameter);

When this command will be executed, following tasks will be performed

1. Instance variable will be created(if variable is declared)


2. Variable will be initialized
3. Reference of the object will be return

Reference of the Object


Every object is uniquely Identified by an ID. This id is known as reference of the object
This reference will be returned to the program, so that program can access object again
and again
Program must create a variable to store reference of the object into it. This variable is
called reference variable.
Data-type of this variable should be that class from which object will be created.

Command to create variable . this will be reference variable


Product p1;
// command to create object and assign reference of the object to the variables p1
P1=newProduct();
i. Product p1 will be created
ii. Object from class product will be created and reference of the object will be
returned
iii. Reference of the object will be assigned to the variable to the variable p1.

Constructor
1. It’s a special type of method
2. Name of constructor must be name of class
3. Return type of constructor is not allowed
4. It is used to initialized objects.

02April2024
What is Az:
During Execution of program some unexpected/ unusual / abnormal condition might
be occurred. These unexpected condition/Situation are known as exception these
exception handling by program otherwise execution of program will be
terminated abruptly.
1. Divide by 0 (Arithmetic Exception)
2. File not found(FileNotFoundException).
3. Databases table not Exist(SQLException).
4. Array index out range(ArrayIndexofBoundsException) etc.
If program is not handling exceptions the JVM will terminates executions of that
program.

What is Exception handling:-


Handling abnormal conditions by the program is called exception handling.
Advantage of exception handling
1. Protecting the program from being terminated.
2. Information the user about abnormal condition.
a. Creating Exception
b. Throwing Exception
c. Catching exception
Creating Exception: Every java program uses following two helpers
1. JVM
2. API (Application Programming Interface): All predefined methods and constructor called by
our program are known as API. When an abnormal occurs, helper creates an object and
stores information abnormal condition into this object is called creating exception.
3. Throwing Exception: After Creating exception, helpers sends that object/exception to the
program to catch it. This is called throwing exception. Actually reference of exception is
sent to the program by JVM or API.
4. Catching Exception: This is responsibility of program to accept exception thrown by
helper. This process is called catching exception.

Exception Classes: These classes are in hierarchical manner every exception class must
be child class/subclass of throwable class either directly or Indirectly

Public class AA extends Throwable


// AA will be exception class
{
}
Public class BB extends AA
// AA will be exception class
{
}
Public class BB extends Object
// AA will not be exception class
{
}

Throwable class has following two child classes


1. Error class
2. Exception class: This class has property of Throwable class it means object of this class
can be thrown it has handling exception property also.
Every has handling exception property also

Error class: it has several child classes. Few of them are as follows
1. VirtualmachineError class
2. NosuchMethodError Class
3. StackOverflowError class etc.
Exception of these classes can not be caught

Exception Classes:
it has several child classes. Few of them are as follows
1. ClassNotFoundException class
2. File not found Exception
3. IOException
4. SqlException
5. RuntimeException class etc
Exception of these classes can be caught

03-04-2024
How to handle exception?
Use try and catch block ho handle exception

Try catch:
Inside this block write those commands that might throw exception
Try
{
//commands
}
Catch block:
Just immediately after try block, write catch block. This block will accept exception
object and display exception message
Catch(ArithmeticException)
{
System.out.println(“Customized message”)
System.out.println(ex)
Ex.printStackln();
}

A try block can have multiple catch block

Few Common exception:


1. A arithmetic exception: this exception is thrown when a number is divided by 0. It
is checked exception JVM creates and throws this exception.
2. ArrayIndexOutOfBoundsException: this exception is thrown an array element is
being accessed beyond the index of array. JVM creates and throws this exception
3. NullPointerException: This is exception is thrown when null referenced variable is
used to call method JVM creates and Throws this exception.
4. FIleNotFoundException: This Exception is thrown when you’re a file is being
loaded and after path is wrong or file does not exit. API creates this exception. It is a
checked exception.

Types of exception:
1. Checked exception
2. Unchecked exception

Checked exception:
Handling these exceptions are mandatory compiler will check existence of handler (try and
catch) in the source code of program. If not found then error will be generated by compiler.
Except Exception class, all child of Exception class are checked exceptions
Public class MyException extends Exception
{
}
Checked exception are also known as compiler time exceptions.

Unchecked exception:
Handling these exceptions are not mandatory compiler will check existence of handler (try and
catch) in the source code of program. If not found then error will be generated by compiler.
Except Exception class, all child of Exception class are unchecked exceptions
Public class MyException extends Exception
{
}
unchecked exception are also known as compiler time exceptions

Finally Block:
Along try and catch block we can write this block also this block is always executed whether
exception is thrown or not and caught or not. So command written inside this block will always
be executed
Try
{
//Command
}
Catch(…….)
{
//command
}
Finally
{
//command
}

Interview Question:
Final,Finally,Finalize
Finalize: Finalize is a method of object class it is called automatically when garbage of an
object is collected

What is garbage Collection?

Freeing memory of the object is called garbage collection in java. This is done by JVM .

Using throw and Throws Keyword:


We can write throw statement and throws statement using throw and throw
keyword

Public int add(int num1, int num2) throws NonPositiveNumberException


{
If (num1<=0 || num2<=0)
{
NonPositiveNumberException ex=new NonPositiveNumberException(“message”);
Throw ex;
}
Return num1+num2;

}
Use throws statement exception created and thrown is checked exception
Type of reference variable:
1. The class which will be instantiated
2. CC obj=new CC();
2)

04-04-24
String handling
===============

What is string?
===============
It is set of characters
For example
"rehanahmad9919@gmail.com"
char type array is required to keep string
Program must create char type array to keep string
You do not need to write code to create this array
This code is already defined in following three classes of library
1)java.lang.String
2)java.lang.StringBuffer
3)java.lang.StringBuilder
Our program will create object from one of the abbove class to keep string.These
classes have several methods.Our program will call these methods to
handle/manage string
Our program can call methods to perform following tasks
1)Compare two string
2)Concatenate
3)Reverse
4)Finding Substring
5)Finding characters from string
Etc.
String str1=new String("Amit");
StringBuffer str2=new StringBuffer("Manoj");
StringBuilder str3=new StringBuilder("Imran");

Note
====
In java reference of the object can not be shown
When you will try to print reference of the object following method of Object class will
be called and value returned by this method will be printed

public String toString()


String str1=new String("Amit");
System.out.println(str1);
//System.out.println(str1.toString());

toString() is a method of Object class


So every class in java has this methos
It will return combination of following three values
1)Class name
2)@
3)Hexadecimal value of object's hash code

Remember parent class method can be overriden by child class


This method is already overridden by String, String Buffer and StringBuilder class.
This method will return string

Note
====
In java reference of the object can not be shown
When you will try to print reference of the object following method of Object class will
be called and value returned by this method will be printed

public String toString()

String str1=new String("Amit");


System.out.println(str1);//System.out.println(str1.toString());

toString() is a method of Object class


So every class in java has this methos
It will return combination of following three values
1)Class name
2)@
3)Hexadecimal value of object's hash code

Remember parent class method can be overriden by child class


This method is already overridden by String,StringBuffer and StringBuilder class.
This method will return string

Methods of String class


========================
It has several useful methods.Few of them are as follows
1)public int length()
2)public char charAt(int index)
3)public int indexOf(char ch)
4)public int lastIndexOf(char ch)
5)public String substring(int formindex)
6)public String substring(int formindex,int toindex)
7)public String toUpperCase()
8)public String toLowerCase()
9)public String concat(String str)
10)public String[] split(String separator)
11)public String trim()
12)public String replace(char old,char new)
13)public String replace(String old,Stirng new)
14)public static String valueOf(int num):This method is overaloed
15)public String toString():This method is overridden
16)public boolean equals(Object obj):This method is overridden
17)public boolean equalsIgnoreCase(String str)
18)public int compareTo(Object obj):This method is overridden
19)public int compareToIgnoreCase(String str)
etc

Equal Method:
It is a method of object class
It Compare reference of two objects and returns a Boolean value string class has
overridden this method. It is compares value of string class object.

Public int compare(Object)


It is amethod of comparable interface
This method can be overiidden to comapare value of two objects it will return either 0
or greater than 0 less than 0
String class has overridden it
String str1=”rohan”
String str=”rahman”’
Int n=str1.compareTo(str2);

Multithreading
It is one of the way to achieve multitasking
Performing more than one task simultaneously is called multitasking we can build
multitasking application by using multithreading A multitasking application creates
and starts multiple threads at a time (per task at a time)

What is thread?
It is a smallest unit of processing
Every thread can vet rated as a program in java every thread is represented in the
form of object.
This object should be an instance of thread class or its child class

You might also like