0% found this document useful (0 votes)
21 views

Javanotes

The document provides information about various Java concepts like data types, variables, operators, control structures, methods etc. It discusses the differences between static, instance variables and local variables. It also talks about type conversion, type promotion and type casting in Java.

Uploaded by

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

Javanotes

The document provides information about various Java concepts like data types, variables, operators, control structures, methods etc. It discusses the differences between static, instance variables and local variables. It also talks about type conversion, type promotion and type casting in Java.

Uploaded by

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

src inside the java jdk folder consists of all the oredefined apis of java

applet
awt
beans
io
net
etc etc

class name should be in capital

jvm calls the main method outside the class

jvm says if it is static method then it is easy for me to not to make the object
and just diectly call the class name

java does not return anything thats why we write void

if any data member is static then it can be called by directly class name

C:\Users\miwsyed\Desktop\JAVAPROGRAMS>javap java.io.PrintStream

declarations not done inside the class if they ared defined in the class

HW

create a class family and get the detai over the console the detail of kal family
the detail includes n of members
total income is for monthly for everyone
addresss
then calculate total income

whatsoever class is made public the name of the file should be as same as the class
name or you will get error

there can be only one public class

if there are 10 clasees then thre will be 10 bytecode created

program should get compiled with class main


jvm calls the main method directly with the class name
becasue main is static main of the class can be called directly without calling the
object because it is static

access modifiers are not allowed with local variables ; public private.

local variables are created in stack

default value is not assigned to the local variables in java

instance variable
it gets memoery over heap
eag object gas its own set of instance variabbles and they can be

instance varuiable is only crated when an object is crated

I modifiers can be ussed with instance variables

instace variables hace default values

for numbers the default value is


for boolean ut us fakse
and for object references it is null

a static body can only access static variable

the value of instance variable is always initialed with as default as 0

but we need to initialise the local variables with somethin


instance variable can have access specifier but local variable cannot have

defualt values are same as of instance variable


a public static final variable behaves as a CONSTANT in java
eg public static final PI / final means you cant change t now its final

in publi void chcek ()


{
int a =3654;
}
here a is a local variable
in class babu {
int a}
here a is a instance variable
get initialised when object is crated

if a variable is outside of the class then it is instance variable but if it is


static then it is static

static is having default initalization as same as instance variable that is 0

local variables cannot have access specifiers

static is also having namee as local variable but in class

instance variables can have access modifiers

you can print instance variables only when you would have made a object

static variable cannot be called from a non static method //// method should also
be statci if you want to call a static method

local variable must be intitialed with somethin or they will give eroor

static variables get initialised wit 0 aswell

everytime instance variable get intitilasde with 0 whenever a neew object is


created

static is independednt of object created it gets incremeneted if there is


+variable

instance variable get independent memory location

static variable get depeendednt there value is changed in the same memory

if there is incrementation in static variable and local variable and new objects
are being made then static will get incremeneted but local variable will be same

DATA TYPES IN JAVA

String is a predefind class

data types ;
Byte b; 1 byte ; 8 bits -2^7(128) to 2^7(127) - 1
Short s; 2 byte ; - 2^15(-32768) to 2^15(32767) - 1
Integer i; 4 byte
Long l' 8 byte
Char c ; 2 byte
Float f ; 4 byte
Double d; 8 byte
boolean bo; 1 bit ?/ no one knows
defualt value for char is null
default value for boolean is false

every datatype is cyclic in nature if you give higher value than the limit than it
will cycle back to the starting values or whatever

//constants are defined in capital //

all the datatypes are predefined in classes known as wrapper classes

by default only lang package is present

H/W what is the reference type of in

make record of student take in marks then declare who got first int this
SCANNER CLASS / this calss is present in util and we need to import it
import.util.Scanner
whenever we take input from the user

the scanner class is having 6 non static methods


non static data member cannor be called directly ; we need to make =object first
and static can be called directly

now for scanner we need to make objects for


Scanner obj= new Scanner(System.in) in is a static variable of input stream class
whatever we enter it goes to System.in
int nextInt()
it is with returntype no argument
so obj.nextInt()
is a return type thats why we need a variable to store the return

for string its next() and to skip a lin it is nextLine()

hasnext is in the string class

type conversion and type promotion is provided me implicitly

type casting we do explicitly

byte short and int get converted to L

compression technique is known as casting


integer type conversion to bye ; big to small ; so typecasting happens and in the
round braces() write what you want it to convert it to

next() stops after the space is entered and stores that into a variable
nextLine() takes input after that space and stores that into another variable
so we need to print the both variables to print the entire sentence
typecasting when we have to assign large datatype size to small size data type that
is done explicitly

byte= 1;
short s = 2;
int i =3;
long l=4;
char c= 'a';
float f=1.2f;
double d=2.3;
boolean bo=false;

long is 8 and i is 4

i = (int) l ;

but if we want to assign int to long small to big is easy so we do it implicitly


l=i;

finally byte gets converted to int

float calclates upto 6 decimal points

byte range -127 to 127 = 256

byte b = 5;
byte c = b*5;// on getting b into expression b gets promoted to int
will give error because int * byte = int and we are saving it into byte so here we
need to typecast b to run successfully
byte c = (byte)b*5;

type conversion and type promotion is done internally by compiler/automatically

and casting is done by the user by putting the desired datatype inside the
parenthesis

CONTROL STRUCTURES ;

if else and stuff

if a particular condition is satisfies then perfrom the action or else ignore the
code

conditional statements;

if (condition)
{body}
if else
nested if
if else if
else has no parenthesis

condition returns true or false


if there is only when statement within the body body is optional
the first line of code will be acc to if codition second line wont be if there is
no body...
if (codition)
SOP ("hey");

if statement doesnt work if there is no condition in the parenthesis


or else just put (true) in the parenthesis

switch ()

statement
break;

and we can write default anywhere inside the switch case

LOOPING STATEMENTS ;

for loop
while
do while
for each loop applied on objects

while loop ;
entry control loop
before printing statement condition is checked
ininitialisization
condition
updation
are done in three seperate ways

do while
exit control loop
first do the opereation the check the condition
in this case the body will get exceuted once
its increment is written in the body

we need to put condition inside the parenthesis of while and do while or else it
will give error
if we write true then it will run infinitely

for(int i=0;i<10;i++)
S.O.P("hey");
S.O.P("hello");
for(int i=0;i<10;)
System.out.println("hey");
will give infnitely hey

for(int i=0; ;)
System.out.println("hey");
infintely prints hey

for(; ;)
System.out.println("hey");
also prints infinitely

jumping statements

break;
continue; skips the next iteration below it and goes to the next one like in
attendance we dont want to take the attendance of rollno 8 so we write continue
below 7 then it will go to next that is 9
return;

TYPES OF METHODS
1.method definition
2.method call

methohd definition has three portion


return type name (list of argument/notmandatory always)
{

actual argument passed when calling the function and in between the parenthesis ;
only the name of variable not definition cuz its been already declared

formal argument ; manually writeen in the function

when calling the

void print(string st)


{
S.o.p("hey "+st )
}

p sum()
{
string s;
s="shailja"
print(s);
}

in int type methods we always write return 0 or 5 or 1


{
int a,b,c;
int print()
{
a=5;
b=5;
c=a+b;

return c;
}
and calling should be as
int p = print();
sop(p);// so the returned int is stored

if not void then


otherwise methods can return 8 types int short float double boolean

Argument space
we can pass
numbers
aplha numeric
objects
pointers are not provided in java in argument space

.length property of java to find the length of string

when object is thrown from main class function to the original function then in
parenthesis type name of the class then any variable

OPERATORS

assignment operators
arithematic
realtional
logical
unary
shift operator
booean operator
combinational operators

a=a+5;
can be written as
a += 5;

logical uniary and shift operator returns binary 0,1

30
-10
0
200
10

relational operators true or false


a=2;
b=4;
sop(""+(a<b));
retrns true

bitwise operatprs also known as logical operatos


works on binary numbers
given 5 it will convert into binary number that is 101 and then it will perform
actin on the binary number
we must have to convert integer
~ ones compliemtn
- means twos compliment / carry get discarded in or opertor
1+1 is 1

a++ means first use a then increment


++a first incremet then use a

SHIFT OPERATORS ;
left shift
right shift
zero filled/ unsigned Right shift operator

int a = 5;// binary is 0000000000000000000101


<< Ls = *
>> Rs = /
ls << 1

on left shitf the empty space is filled with 0


that give a*2^1
5*2
10

study right shift bru


zerp filled right shift

212 binary is 11010100


ls << 1

whenever you right shift a nev=gative number the answer is one greater than the
actual result

WAP TO CRATE A MENU FOR A RESTAURENT THERE YOU ARE PROVIDIN G THE CUSTOMER TWO
OPTIONS VEGETARIA NAND NON VEGETARIAN
WHEN THE USER SELECTS A DISH THEN THE PRICE WOULD BE SHOWN USING INNER SWITCH ;
SWITCH WITHIN SWITCH

what is public static void main


what is the meaning of System.out.print
System is a class
out is a variable of type static

for each loop


enhanced for loop
3
10
31
38
53
63
70
for (int i=0;i<e.length;i++)
{e[i]=andar.next()
}for (int i:e)
take a value from e of 0 assignt it to i // automatic increment that is transfers
all the value into array
it will print all the emelents of the array not the mid
ARRAYS ;

static array
dynamic array

by default object holds null value

//Enter information of 4 students there Name,Roll no and Section using array

import java.lang.*;
import java.util.Scanner;
class Student
{
Scanner scan= new Scanner(System.in);
String student;
int rollNo;
String section;

void read()
{ System.out.println("enter the name of the student: ");
student = scan.next();
System.out.println("enter the roll number of the student: ");
rollNo = scan.nextInt();
System.out.println("enter the section of the student is : ");
section = scan.next();
}

void display()
{
System.out.println("name of the student is : "+student);
System.out.println("Roll number of the student is : "+rollNo);
System.out.println("Section of the student is : "+section);
}
}

class Information
{
public static void main(String args[])
{
Student obj[] = new Student[4];
for(int i = 0; i <4 ; i++)
{
obj[i]=new Student();
}

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


{
obj[i].read();
obj[i].display();
}
}
}
passing array as an argument;

h/w
take the detail of studet
his marks in one subject
his name
take all this in main method
for three students
throw this information to some method calculate which belongs to some another class

and the calculate method is adding 5 marks grace to the marks of student and then
returning the incremented marks back to the call area i.e main method /// array of
object as argument

generic array list

if array needs to store integer type and also

ArrayList <String>a = new ArrayList();


a.add("Abc");
a.add(1);

arraylist is having by default capacity 10


if we are giving 11 as size then it is incremented as 10
size ; how many objects
capacity ; if we add 11th lement then it gets incremented by 10 so capacity =20

capacity formula = (old capacity * 3 / 2) + 1


i.e 16

CLASS INHERITANCE

polymorphism

UPCASTING

when smaller value is directed towards the


DOWNCASTING

//objects of string class are immutable

but value of objects of String class can be changed


using StringBuilder class
sb.append("xyz");
StringBuffer : the data
it will store the data in an temporary buffer

StringBuffer is not sequential you need to clear the previous value using
nextLine();

by default capacity of all three is 16//

we write contants in java with all capital


public static final A=5;

enum Day
{
//what evers in it is a object//
SUNDAY , MONDAY , TUESDAY , WEDNESDAY , THURSDAY , FRIDAY, SATURDAY
}

enum objects are predefined you cannot new it

value of tells the whether the object is present or not

enum has constructors same as class

topic :

LOCALDATE

if you want to print a specific date

// OF MEHTOD TAKES THREE ARGUMENTS


e. Locadate.of(2018,Month.februaury,20)
parse method takes argument as String

parse to take about specific date takes string type format (yy/mm/dd/h/m/s/ns)
SINGLETON CLASS

can create only one object in static method and return type should be class type

and its constructor is private type

to access the method from another class

class A
{
private a()
{A a = null;}

static A read ()
{
if(a==null)
A a = null();
}
return a;
}

class B
{
p sum()
{
A.read();
}
}

by default the constructor of singleton class is private

ABSTRACT CLASSES
having abstract infront of the class// it is used for data hiding // methods int
his class are just made not code written eg abstract method() {} //we cant make
object of abstract class because
when any class is abstract then it can have an abstract method or not but if it is
then the abstract method should be defined in the child class//its constructor is
protected thats why we cant make objects// for inheritance of a normal class or
abstract class we write implements
for inheritance of interface class we wrtie extends
abstract class ::::: its child class is also abstract then it can provide
definitions to some of the methods of its super class

interface // makes alot of abstract methods//purely having abstract methods


same as of that of class but all the methods in the interface are abstract
methods// we need to override all the methods//interface can only have
default(access specifiers) methods or static methods when you want to provide
definiion//object of interface cannot be created //it does not have constructor at
all///the child class should be an abstract class /// interface is public by
default

interface Game
{
void wayofplaying();//this is an abstract method
}

to define either we can define in normal class or if in interface we need to write


default or or static with a method like default void wayofplaying()/// or if we
define it in abstract class we need to write abstract behind the method//

if we dont want to give denition of interface then in child make class as abstract

for inherting an interface the keyword is implements

the child of the interface should have a strong access specifier like public

the methods should be public in subclass where it are defined

(public>protected>default>private)
maximum access means is strongest

or we get error of weaker access previlage error comes when stronger to weaker

in normal class the be defualt methods are default


interface()
{
void tiger();
static void run();
{
S.O.P("babli miss")
}

default void rund();


{
S.O.P("babliii miss")
}

and to run

we do Animals.run(); // we can directly call static methods and for default we need
to make an object from subclass
can we override static method ??

a class inplemets interface but an interface extends interface but a class extends
another class

interface Vehicle
{
void speed();}

interface Gaddi extends interface Vehicle


{

static method can never get overridden

multiple inheritance is allowed with interface


function gets hidden

interface Vehicle
{
void speed();
}

interface Car
{
void speed();
void mileage();
}

class Lincon implements Car,Vehicle


{

public void speed()


{
System.out.println("badia");
}
public void mileage ()
{
System.out.println("Wo b badia");
}
}

class Main
{
public static void main(String args[])
{
Car obj = new Lincon(); // for object definition it goes to lincon and
for method it searches in Car
obj.speed();
obj.mileage();
}
}

INNER CLASS

class in another class


class human
{
int age;
Sring name;
class Adharcard
{
int id;
void purpose();
}
}

annonymous class should be an inner class


inner class has 3 type statc, non static, annonymous

ovverride the methods without creating the new class

class human
{
in age;
void getAge();
{}
}

class Abc extends human


{
PSVM(){
human obj = new human() // means do not call constructor
{
int age = 50;
void getAge()
{
SOP("hey");
}
}

}
} // annonymous inner clas because it is made in main
nested Class

when there is a method which has its own attributes in a class we use nested class
to define its own attributes

lambda expression
applicable on interfaces and abstract class
in annynomous class there is even no need to write the name of the class

You might also like