- Java was initiated by
James Gosling, Mike Sheridan and patrick Naughton
atsun Microsystems
in1991
- initially named as
Oak
- Originally designed for interactive TV
- Before jdk 1.6 , java was not pure object oriented programming because it used variables not objects that is using primitive
data types
instead of projecte.g,. int a;
- Though from
jdk 1.6
orjava 6
, it started usingwrapper
classes to becomepure object oriented programming
- wrapper classes these are used to make objects of primitive data types
e.g., Integer a=new Integer(5);
-
Simple
- Syntax similar to C++
- no use of pointers
- no need to remove unreferenced pointers
-
OOP's
- Pure Object oriented language because we are not able to execute a single line of statement in java without using class and objects
(Interview special)
- Pure Object oriented language because we are not able to execute a single line of statement in java without using class and objects
-
Platform Independent
- Once a program is compiled then it can run anywhere and in any system
- not produce machine specific code
- software based platform independence
- Software run on top of other platform
- It has 2 components:
- Runtime environment
- Application Programming Interface
- Inside
.exe
file the code is translated to OS internal commands in C++ - For example , a
print
statement replaces withdisplay
function to print something onwindows
console in C++ - In Java , after compiling the file created is
.class
and not.exe
- The
.class
file containsbyte code
and is read byinterpreter
at run time - JAVA program runs inside JVM
- Uses run time environment of its own
-
Robust
-
Portable
-
High Performance
-
Multi Threading
-
Dynamic
-
Interpreted
- Class Loader seperate local file system form network imported files
- byte code verifier to check the code frament for illegal code
- Collection of member variables and member functions
- blueprint to construct object
- By default all members are public in JAVA
- User defined data type
- It has access specifiers private, public, protected
- class is a logical representation
- Things defined inside class are the properties of the objects
- Example
class Lamp
{ // instance variable
private boolean isOn;
//method
public void turnOn(){isOn}}
- instance of a class
- Object is a real world entity
- Need object to access class members
class Lamp
{
public static void main(String[] args)
{
Lamp l1 = new Lamp(); // create l1 object of Lamp CLass
Lamp l2 = new Lamp(); // create l2 object of Lamp Class
}
}
// Object is ```new Lamp```
// l1 is a referenced variable of specified class
- show only essential details
- focus on what class can do and what it must do
- Done in java using interface
- e.g., Email send system
- A phenomena by which we just show essential details to the user and hiding the rest
- Wrapping up of data together into a single unit class
- hiding data
- focus on how to achieve the functionality
- Done in java using access modifiers
- e.g., CSE department
- binding the accessibility of some variable inside a class
- Inheritance is the process by which we can use existing code
- Inheritance is the property by which object of one class can acquire the property of other class
- Base Class or Super Class the class which has main properties
- Derived Class or Sub class inherits the existing properties of a class
- Reusability of code
- Multiple inheritance of classes is not allowed in
JAVA
because ofDiamond Problem
and it has a solution ofVirtual Classes
- virtual classes requires pointers but there are no pointers in java
- Single Level Inheritance
A | B
- Multi Level Inheritance
A | B | C
- Multiple Level Inheritance (#### Not present in JAVA)
B C |___________| | A
- Hierarichal Inheritance
A ____|____ B C
- One name many forms
- It depends on the instance of objects
- It can be achieved using
method overloading
- It is of 2 types
- Static Polymorphism ( compile ) -> method overloading, constructor overloading
- Dynamic Polymorphism ( run time ) -> method overriding
int getdata (int,int) //1
void getdata(int,int) //2
int getdata(float,float) //3
void getdata(int,float) //4
int getdata(float,int) //5
/*
1 & 2 are not overloading
1 & 3 are function overloading
1 & 4 are function over loading
1 & 5 are function over loading
*/
- 3 rules to find overloading(polymorphism)
- ignore the data type declaration ( int, void, char etc)
- Name of methods should be same
- no of arguments or types of arguments or order of argument should be different
JVM
is the component due to whichjava
is verypowerful
- It is a combination of
java interpreter and operating system
- It requires compiled file
.class
- Communicates between
.class
file and OS - Decodes the
.class
file - JVM is platform dependent and because of JVM java programs are platform independant
JAVA SOFTWARE
is platform dependant but not itsprograms
- JRE is a collection of
JVM + Java Libraries
- Collection of
JRE + Java Development Tool Kit
isJDK
- The
.class
file contains encoded instruction for the java interpreter and are known as java byte code
-
Data types are of two types
- Primitive -> defined in language by default
- Non Primitive -> user defined data structure
-
Primitive Data Types
- Numeric
- Integer (Int, Float or Double)
- Character (char)
- Boolean
- Numeric
-
Non Primitive array,stack,queue
-
Types of Size 32 - bit System
- (1) byte
- (2) short
- (4) int
- (8) long
- (2) char
- (4) float
- (8) double
64 - bit system
- (8) float
- (16) double
- (1) boolean
till jdk 1.3
- (1 byte) boolean
after 1.3 jdk
-
Short is important and char is also used in short
- b < S < I < L < F < D these are data types
- this narrowing is not allowed in java
- In short or integer type data type , the storage size is 15 bit due to presence of signed bit
- In char data type , the storage size is 16 bit as there is no signbit
- 2 byte = 16 bit
- Name of a memory location
- Each variable has a datatype
- 4 rules to define a variable are:
- the variable name should not start with a numeric digit
- variable name should not contain any whitespace
- variable name should not contain any
language keywords
orprimitive words
- We can not use special character except
_
- There are 3 types of variable
- Local Variable
- Instance Variable
- Static Variable
- Local Variable ~> Variable defined inside a method and accessed inside that method only
- Instance Variable ~> Value is object specific , value not shared with other instances , Declared inside class but outside the body of method
- Static Variable ~> Declared with static keywords , Shared among all instances , Memory allocated once at compile time, Should be initialized first that is each object will be able to change value of class variables and values will be modified for each object
class Demo
{
int a = 50; // instance variable
static int b = 100; // static variable
void func()
{
int x = 90; //local variable
}
}
- Collection of homogenous items stored under one name
- size is fixed
- it can be used as a object
- Syntax
// pre declaration of array
int[] a1 = new int[5]; // type name[] = new type[size]
// post declaration of array
int a1[] = {1,2,3,4,5}; // array as referenced variable = size
int []a, b, c[]; // pre declaration gets associated with all variables till semi-column in its right side
// here a is 1d array , b is 1 d array and c is 2d array
- no of columns can be variate in JAVA
- To find the length or size of array that is no of elements in array, we use the function
variable-name.length
- For 2D array,
variable-name.length
will return no of rows andvariable-name[i].length
will return no of elements inith
row - For 3D array,
variable-name.length
will return no of 2D array in 3D array
int [][]a[]= new int[6][4][2] // 3D array
/*
| [ [ ] ] | [ [ ] ] | [ [ ] ] |
*/
```
|0|1|2|3|4
|0|1|
|0|1|2|
|0|2|3|4|5|6|
|0|
```
- 2D Array
int a[][] = new int[5][4];
int []a[];
int [][]a , b[]; // 3d array
- built using values,variables, operators and method calls
- (a2) is an expression and b+ (a2); is a statement
- Expression is a clause, and the statement is the complete sentence since it forms the complete unit of execution
- expression produces intermediate result
- produce a value
- assign a variable
- those that have no result but have a side effect because an expression can include a wide range of elements such as method invocations or increment operators that modify the state.
- symbols that operates on one or more arguments to produce results
- Arguments here are operands
result = a+b
- Assignment operator
- lvalue = rvalue -> rvalue is assigned to lvalue
- Arithmatic operator
- Relational Operator
==
and!=
are object reference operators
- Logical Operator
AND (&&) OR(||) NOT(!)
- Logical Operator bit level
AND & OR | XOR ^ NOT ~
int a= 10; // 00001010 = 10 int b = 12; // 00001100 = 12
- logical bit wise opeator checks first condition before proceding further
- logical operator checks all conditions before taking any conditions
- Number is represented into 32 bit(Theoretically)
result = a & b * result is negative then the answer will be 2's complement
- Shift Operators
- Shift Operators(bit level)
- Shift Left
<<
Fill with zeros - Shift Right
>>
Based on Sign- if number is positive then it will be filled with
0
- if number is negative then it will be filled with
1
- if number is positive then it will be filled with
- Shift Right
>>>
Fill with zeros
a = 0011 a << 2 0011 ~> 001100 a >> 2 0011 ~> 0000 b = -4 b >> 2 111111111111111111111111100 ~> 11111111111111111 0100 ~> 0001 -4 ~> -1 (twos complement) a >>> 2 0011 ~> 0000 3 ~> 0
- Block of program to change the execution of program based on logic and values
- 3 types of control structures are:
-
Conditionals
- IF
if (condition) { //codes } //codes after if
- if else
if (condition) { } else if { }
- nested if else
- switch
switch (condition) { case 1 : //code case 2 : //code }
-
loop
- For
for(initialization;testExpression;update) { //code inside for loop's body // to run it for infinite just testExpression == True }
- While loop
int i = 0; while(condition) { statement condition update }
- Do While
- It executes atleast once
-
Jump Statements
- unconditionally transfer the program control to another part of program
- Continue
- Break
- Return ~> it immediately quit the current method and return to the calling method
class class-name-user-defined{
// access-specifier method-static void main(String[] args)
public static void main(String[] args){
... .. ...
n=3;
result = square(n);
... .. ...
}
private static int square(int i){
// return statement
}
}
// static method ~> we dont need any object to call the function/method
// String[] is a variable length array which stores the input from cmd
// args is just a variable name which can be user-changeable
-
file name should be similar to class name but its not compulsory
-
at compile time we need
file-name.java
-
at run time we need
class-name.class
<-----------------The End of Unit 1---------------------->
- To run any code
- Save the file with code
- Open cmd and run
javac file-name.java
- it will create a
.class
file - to execute
java file-name
- Default package always associated with java code is
java.lang
- Any word starting with
Capital Letter
is aClass
- All methods are iitiated with
small letters
- To take input we use class
java.util.*
Scanner sc=new Scanner(System.in); // object of the same class System.out.print("enter the value of a: "); a = sc.nextInt(); // Camel Notation used in java // nextInt works same as scanf of C
random
class produces17 decimal place
digit- Static method can only call other Static methods
- Syntax
for(data-type variable:iterable-structure)
for(int i:a[])
further code
- String ~> An array of characters is called String
String
is also aclass
in java which can be used by making objectsString s = 'Deepak';
- String objects are immutable
- While creating the first object of any String always
2 objects
are created - The two objects created are
Heap
andConstant
- when creating further objects of similar String, the compiler checks the constant object for availablity , and if available then link to its reference else create another
Heap
- The Heap object is used to process or compute the String with other commands and Constant for Similar String checking
- It is a functionality of java where Strings are compared with each other based on their referecnce variable and not on their actual value
- To compare two strings we use the function
string-variable-name.equals(another-string-variable-name)
- To compare two strings without
CaseSensitive
we use functionString1.equalsIgnoreCase(String-2)
- To convert String to
Lower Case
use the functiontoLowerCase()
- To convert String to
Upper Case
use the functiontoUpperCase()
- To find the charater in a string with
index
position use the functionstring-name.charAt(index-position)
- Constructor can be made
private
usingSingle Turn Pattern
-
To inherit one class in another , we use the function
extends
-
All the classes being inherited by a
Derived
class are written seperated by,
// created a base class class Super // Java has a inbuild keyword super { int a = 0; public void show() { System.out.println("A="+a); } } // created a derived class class Sub extends Super { int b = 0; public void display() { System.out.println("B="+b); } }
-
if we do not define a specific
constructor
in a class thencompiler
creates a constructor for the sameclass
so that a user is able to makeobject
of theclass
-
We have three types of constructor
- Default ~> to initialise the variable with default data types
- Parameterised COnstructor ~> Initialse the variables of the class defined by user at run time
- Copy Constructor ~> Previously existing objects are used to create new objects
-
Constructor of Super Class can not be called in the derived class just by using its name
-
To call the constructor
Base
class inside theDerived
class we use the functionsuper();
-
If we are using
super
keyword then it must be theFIRST
executable keyword in theSub
orDerived
class created by theuser
-
If you define same variable as
argument to a function
and to be assigned, we can use keyword to differentiate the varaiablesclass Sub extends Super { int b = 9; public Sub(int b) { super(); // it calls the constructor of the Base Class this.b=b; } }
- Same name with different names or arguments
- Same name with same number and name of arguments
class Super
{
int a;
public Super(int a) // constructor
{
this.a = a; // instance variable
}
public void show()
{
System.out.println("A=" + a);
}
}
class Sub extends Super
{
int b;
public Sub(int b)
{
Super(b*2);
this.b = b;
}
public void display()
{
System.out.println("B="+b);
}
}
class Day4Demo
{
public static void main(String args[])
{
Sub obj = new Sub(10);
obj.display();
}
}
this
it differentiates instance variable with arguments- In Inheriatnce(overriding) , the top variable(variable of base class) can store the Sub/Derived class object or variable where as Sub/Derived class can not do so
Sub obj = new Super(10); // not possible
// where as
Super obj = new Sub(20); // is possible
class Add
{
int a , b;
float c;
public void getAB(int a,int b,float c)
{
this.a = a;
this.b = b;
this.c = c;
}
public void Sum(int a , int b)
{
System.out.println("Sum ="+(a+c));
}
public void Sum(int a, float c)
{
System.out.println("Sum = " + (a+c));
}
}
class DayOverriding
{
public static void main(String args[])
{
Add obj = new Add();
obj.Sum(2,3);
obj.Sum(2,2.5); // By default double
}
// Sum =5
// Sum = 4.5
}
- Abstract Class
- Static Class
- Inner Class
- Package
- Interface
- Wrapper Class,Access Control
- Super,this,final keywords
- A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods
- Abstract is a process of hiding the implementation
- It shows only essential things to user and hides the internal details
- Ways to achieve abstaction
- Abstract Class (0 to 100%) ~> depends on developer
- Interface ( only 100%)
- Implementation
- must be declared with
abstract
keyword - may have abstract method and non abstract method
- must have
Atleast One
abstract method and vice~versa - it need to be
extended
means need to implement inherited- the abstract class will be the super class and need to be inherited in some class
- it cannot be
instantiated
, means we can not create object of abstract class
- must be declared with
- a method without definition is known as abstract method
- it must be declared with abstract keyword
- It must be override in sub class otherwise subclass will become abstract
- Syntax:
abstract void function-name();
//abstract return_type Method_Name(ARGS)
abstract void fun(int,int);
abstract class Demo{
int a,b;
abstract void fun(int,int);
void getdata(){
a=10;
b=20;
}
}
- Interface is a process to achieve abstraction
- interface is the just a blueprint of a class
- it has
static
andfinal
variable ~> value will be constant for all objects - it has only
abstract
method - interface always be implemented
- it cannot be instantiated just like the abstract class
- It is not a class itself but tells the structure of the class
- Interface must be
implemented
where as class must beextended
forabstraction
- interface is a collection of abstract methods and constants
- Can not create
object
ofinterface
- All methods declare in an interface are public abstract by default
- Till
JDK 1.7
, Non abstract methods are not allowed in interface - From
JDK 1.8
, we can definenon-abstract methods
insideinterface
as well - Everything defined inside interface is public by default
// A function with definition but do nothing can be stated as
void func-name()
{
}
class A{
//declaration and definition
}
interface A{
//declaration only
// all methods will be abstract
//
}
interface name_interface{
//declare variables
//declare methods
}
interface Animal()
{
int legs=4;
void fun();
}
- Class extends Class
- Class implements Interface
- Interface extends Interface
(interface) (interface)
| |
implements |_________________|
|
(Class)
(interface) (interface)
| |
|___________________| (extends)
|
(Class)
- A java package is a group of similar types of classes , interfaces ad sub-packages
- Package in java can be categorized in two form, built-in package and user-defined package
Abstroict window Toolkit
isAWT
- There are many buil in packages such as java,lang,awt.javax,swing,net,io,util,sql etc
package Name_Package;
import.....;
class......{
statement...
}
// package must be the first line inside the source code file
- Name_Package is the full path of directory separated by
.
- E.g.,
Desktop.Ju-Notes.JavaCode
javac -d directory javafilename
javac -d . Demo.java # example 1
- Package is used for classes in which main class function is not included
- It is of 2 types
- Access Modifiers ~> Defines the accessibility limitations
- Default
- Private
- Protected
- Public
- Non-Access Modifiers ~> it defines the functionality but not the accessibility
- Static
- Abstract
- Final
- Synchronized
- Modifiers provide some kind of feature or limitation to an data structure like class or object or methods
Access MOdifier | within class | within package | outside package by subclass only | outside package |
Private | Y | N | N | N |
Default | Y | Y | N | N |
Protected | Y | Y | Y | N |
Public | Y | Y | Y | Y |
- Java
inner class
ornested class
is a class which is declared inside the class or interface - We use inner classes to
logically group
classes and interfaces in one place so that it can be more readable and maintainable, that is keeping data which is dependable upon each other can kept together - It can access all the members of
outer class
includingprivate data members and methods
- It is a part of nested class
- Non static nested classes are known as inner classes
- It can access all the members (data members and methods) of outer class including private
- Non static nested class
- Member inner class ~> normal inner class
- Anonymous class ~> name is defined by compiler at the runtime, a class without name
- Local Inner class ~> class which is defined inside a method
- Static class
- Static nested class
- Name is decided by compiler
- Used in Artificial Programs
// Anonymous inner class
abstract class Demo{
public void show();
}
class testDemo{
Demo p=new Demo(){ // Anonymous class... name will be decided by compiler at run time
public void show(){
S.o.p("Hello Demo");
}
};
p.show();
}//end test demo
// another example
Demo1 d = new Demo1(
new TestDemo(){ // starting of syntax of anonymous class
void data()
{
...
}
}
);
// TestDemo is abstract class
class Demo{
public void display(){
class inner{
public void show(){
SOP("Local inner ");
}
}//local class ends
inner obj=new inner()l
obj.show();
}//display ends here
}
- can access static data members of outer class including private only
class outer{
static int a = 10;
int b = 20; // not accessible
static class inner{
public void show(){
s.o.p("value od a="+a);
}//show ends
}//inner class ends
}//outer class ends
- it can be applied to variable, method and class
- if we make a variable as final, then it become the constant. That means values of that variable can't be changed
- If we make a method as final then it can't be overridden . That means overriding of final methods are not allowed
- If we make a class as final then it can't be inherited
- The super keyword in Java is a reference variable which is used to refer ommediate parent class object
- super can be used to refer immediate parent class instance variable
- super can be used to invoke immediate parent class method
- super is used to invoke constructor of
Super
orbase
class
- this can be used to refer current class instance variable
- this can be used to invoke
current
class method (implicitly) - this() can be used to invoke current class constructor
- this can be passed as an argument in the method call
class Demo{
Demo(int a){
x = a;
}
Demo(int a, int b){
y=b;
this(a)
}
Demo(int a, int b,int c){
z = c;
this(a,b)
}
}
- Compile Time Error -> Some kind of
Syntax error
- Run Time Error -> Not run due to
environment error
- Logical Error -> Compiled and run but Error in some code input due to which we are not getting desired output
Exception
are the cause by which our programs get terminated or giving some wrong output- If we get such error at
compile time
then Exception is known asCompile time
exception in our program - If we get such error at
execution time
of the program then such errors are known asRun time
exceptions
Check
andUncheck
exceptions are with respective to thecompilers
point of view
-
Compile Time Exception
- These are also known as
checked exceptions
- Examples
- I/O Exceptions
- SQL Exceptions
- These are also known as
-
Run Time Exception
- These are also known as
unchecked exceptions
- Examples
- Arithmatic Exception (due to some calculation mistake)
- Array Index Out of Bound Exception
- These are also known as
- There are two ways to handle
exception
-
Throw
- All exceptions will be handled by compiler only
- Program always gets successfully compiled
Class ABC{ P.S.V.M(String args[]) throw { ...... ...... // Exception occur ...... } }
- Does not compile when error occurs due to package missing issues
- We can define the particular
name of package
for which error may occur e.g.,IOException
- or just define the main class
Exception
-
Try , Catch , FInally
try { //Exception Code... the line of code in which we are expecting some exception to be generated } catch (Exception e) { // corrective measure of exception occurring in upper block that is in try block } finally { // it is executed always whether we are having error or not }
- If we are defining
try
block then atleast onecatch
block is necessary to be defined - finally block is not necessary to be defined , its upto the developer
- It is of 3 types:
- Try_catch with single catch
- Try_catch woth multiple catch
- Try_catch with nested try_catch
- If we are defining
-
- Generating a self customized exception and terminating the program as per our need
- I/O stream can be implemented by two ways:
- Sequence of bytes
- Sequence of characters
File handling is performed using IO Stream
- Stream can be defined as flow of data
- To work with any Stream, follow the steps:
- Import the specific stream package
- Create the object of concern I/O Stream
- Determine The input (make source using CLA or at compile time) and output points for work to be performed
- Object is supermost class of Java,for both pre-defined and user-defined classes
- Every Stream should be closed
.close()
before exiting the program
- A stream is a sequence of data and is composed of bytes
- Default Stream: System.out,System.in,System.err, all are connected to console only
- Each class has an Input and Output Stream
- Available Classes are of 7 types:
- Input (SYstem.in)
- Output (System.out)
- Filter Stream
- Buffered Stream ~> Tends to save the inputs to input stream and output to output stream which makes it faster at the moment of execution
- Data Stream ~> Used in networking tasks , A socket is generated between 2 systems trying to communicate with each other
|A|~~~> (Socket)~~~>|B|
- Print Stream
- File stream ~> Specifically used for
File Handling
- to send some errors we can use
System.err
- Reader and Writer
- It is again of 4 types
- Input Stream Reader
- Output Stream Writer
- Buffered Stream Reader/Writer
- File Reader/Writer
- Java.io is an abstract class for all input stream
- Basic
read()
method read a single unsigned byte of data and returns the integer value of the unsigned byte read()
returns-1
at the EOF- Every input stream should be closed before exiting the program
- I/O is slow in comparison to memory access, limiting the number of reads and writes is essential
- The basic read() method only reads in a byte at a time
- The following two overloading read() methods read in multiple bytes into an array of bytes
- public int read(byte b[])
- public int read(byte b[], int offset=2)
- It obtains input bytes from a file.It is used for reading byte oriented Data
- To print certain character after reading using
Input Stream
then it will be required to change into character usingchar()
method. - To typecast a certain variable the syntax is like
(char)variable_name
- during file handling,when
file.read()
reachesEOF
it returns-1
fil.read()
~> it does the work of fetching character as well as iteration of next byte/character
import java.io.*;
class FileInputStreamDemo{
public static void main(String args[]){ //CLA - command line arguments
try {
//Create a file input stream
FileInputStream fis= new FileInputStream("Path" args[0]);
//read 12 byte from file
int i;
while(i=fis.read() != -1) // at EOF byte is -1 which indicates the end of file
{
System.out.println(i);
}//close file output
fis.close()
}catch(Exception e){ System.out.println("Exception:"+e)}
}
}
- An example of Buffered Input Stream, it will increase the Execution Speed of the Program
import java.io.*;
class FileInputStreamDemo{
public static void main(String args[]){ //CLA - command line arguments
try {
//Create a file input stream
FileInputStream fis= new FileInputStream("Path" args[0]);
//read 12 byte from file
BufferedInputStream bis = new BufferedInputStream(fis);
int i;
while(i=bis.read() != -1) // at EOF byte is -1 which indicates the end of file
{
System.out.println(i);
}//close file output
bis.close()
fis.close()
}catch(Exception e){ System.out.println("Exception:"+e)}
}
}
-
public void write(int)throws IO Exception ~> is used to write a byte to the current output stream
-
public void write(byte[])throws IOException ~> is used to write an array of byte to current output stream
-
public void flush()throws IOException ~> flush or remove the current output stream
-
public void close()throws IOException ~> close the current output stream
-
FileOutputStream~> it is an output stream used for writing data to a file
public class FileOutputStream extends OutputStream
- Methods in FileOutputStream are:
- protected void finalize()
- void write(byte[] ary)
- void write(byte[] ary,int off,int len)
- void write(int b) and many more
import java.io.FileOutputStream;
public class FileOutputStreamExample{
public static void main(String args[]){
try{
FileOutputStream fout = new FileOutputStream("path of file");
// to connect it with a buffer
//BufferedOutputStream bout = new BufferedOutputStream(fout);
fout.write(97); // instead we will use bout.write(97); and bout.flush();
// flush() is used to forcefully write if some error occurs due to network issues
fout.close();
System.out.println("Success");
}
catch(Exception e){
System.out.println(e);
}
}
}
import java.io.FileOutputStream;
public class FileOutputStreamExample{
public static void main(String args[]){
try{
FileOutputStream fout = new FileOutputStream("path of file");
String s = "Pykid";
byte b[] = s.getBytes(); //converting string into byte array
fout.write(b);
fout.close();
System.out.println("Success");
}
catch(Exception e){
System.out.println(e);
}
}
}
(Will be taught later)
- Thread Life Cycle
- Multi Threading Advantage and issue
- Threading Synchronization
- Introduction to AWT Programming(Abstract Windowing Toolkit used for designing GUI)
- Layout, COmponenet and Event Handling
- Applet PRogramming
- Swing Component(All components in AWT and swing are same)
- AWT components(Presentation and not working) are dependable on OS Platform where as Swing isn't
- Naming Difference in AWT and Swing is there ( JLabel(Swing) ~> Label (AWT) )
- Layout ~> Decision Taking as to where the component is to be added
- Component ~> Everything visible in a GUI is a component
- Container ~> It contains components. e.g., Frame/Window
- Panel ~> Used when we have some limitation, in panel components are added and Panel is used as an component is Frame
- Event Handling ~> Controls the working of our GUI either click or drag or type everything
- Applet is an java program that is implemented in HTML Code(will be studied later)
- A process needs to perform
Context Switching
to communicate with other processes which is not required with threads - Each process has an seperate address in memory
- If in a program no threads are defined then it means it has
1 internal thread
running in it
- Thread is a
smallest unit of process
or lightweight sub-process Multi threading
is a process of executing multiple threads simultaneously- Multiprocessing and Multi Tasking is used to achieve multitasking
- Threads used a
shared memory area
that is the sameaddress space
- It is mostly used in Games and animation
- It doesn't block the user because threads are independent and you can perform multiple operations at same time
- saves time as many operations can be performed together
- Threads are
Independent
, so it doesn't affect other threads if an exception occurs in a single thread
- start() ~> To start a thread
- run() ~> to do an action of thread
- getName() ~> gives name of thread
- setName() ~> changes name of thread
- getId ~> return id of thread
- isAlive() ~> tests if thread is alive
- yield() ~> pause current running thread temporarily and allow other threads to run
- There are four states of a thread life cycle
- New ~> Thread is just created
- Runnable ~> Thread is ready to execute (after start() method is called )
- Running ~> Thread is executing (after run() method is called)
- Terminated ~> Thread is completed or aborted
- Java AWT(Abstract Window Toolkit) is an API to develop GUI or Window-based applications in java
- Java AWT components are platform-dependent
- WT is heavyweight i.e, its components are using the resources of OS
- The java.awt package provides classes for AWT api such as TextField , Label,TextArea,RadioButton, CheckBox , CHoice ,List etc
- The Container is a component in AWT that can contain another components like buttons, textfields etc. The classes that extends COntainer class are known as container such as Frame , Dialog and Panel
- Panel is never visible unless a component is added to it and The panel is fixed to a specific layout
- Useful Methods of COntainer Class are:
- public void add(Component c) ~> Inserts a component on this component
- public void setSize(int width,int height) ~> sets the size(width, Height) of the component
- public void setLayout(LayoutManager m) ~> defines the layout manager for the component
- public void setVisible(boolean status ) ~> changes the visibility of the component,by default false
- By default layout is Flow Layout
import java.awt.*;
class DemoAWT extends Frame{
DemoAWT(){
Button b=new Button("Click me");
b.setBounds(x1,y1,x2,y2); //setting button position
add(b); //adding button into frame
setSize(300,300); //frame size is 300x300;
setLayout(null); //no layout manager
setVisible(true); // now frame will be visible, by default not visible
}
public static vod main(String args[]){
DemoAWT obj=new DemoAWT();
}
}
-
Changing the state of an object is known as an event
-
Event Classes ~> Listner Interface(Action Perform)
- ActionEvent ~> ActionListner
- MouseEvent ~> MouseListner and MouseMotionListner
- MouseWheelEvent ~> MouseWheelListner
- KeyEvent ~> KeyListner
-
We can define the definition of a button with its declaration only by using
anonymous class
- The Layout Manager are used to arrange components in a particular manner.Layout Manager is an interface that is implemented by all the classes of layout manager
- BorderLayout ~> Used to arrange the components in five regions where each region may contain one component only.
- NORTH ~> public static final int NORTH
- SOUTH ~> public static final int SOUTH
- EAST ~> public static final int EAST
- WEST ~> public static final int WEST
- CENTER ~> public static final int CENTER
- If Single Component is added, it takes the space of all other regions as well
- The GridLayout is used to arrange the components in rectangular grid.One component is displayed in each rectangle
- Constructors of GridLayout CLass
- GridLayout() : creates a grid layout with one column per component in a row
- GridLayout(int rows, int columns) : creates a grid layout with the given rows and columns but no gaps between the components
- GridLayout(int rows,int columns,int hgap, int vgap) : creates a grid layout with the guven rows and columns alongwidth given horizontal and vertical gaps
- Applet is a special type of program that is embedded in the webpage to generate the dynamic content.It runs inside the browser and works at a client side
- It works at client side so less response time
- Secured
- It can be executed by browser running under many platforms, inlcuding Linux,Windows , Mac OS etc
- Plugin is required at client browser to execute applet
- Applied when components are required to be structured over one another
- Makes the above component disable or invisible making the below component active or visible