java notes (1)
java notes (1)
com ,
https://www.tutorialspoint.com
Java Version History
Java language developed by company Sun Microsystems and the creator
is Jamesh Gosling.
Some of the versions of java are
JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan, 1996)
JDK 1.1 (19th Feb, 1997)
J2SE 1.2 (8th Dec, 1998)
J2SE 1.3 (8th May, 2000)
J2SE 1.4 (6th Feb, 2002)
J2SE 5.0 (30th Sep, 2004)
Java SE 6 (11th Dec, 2006)
Java SE 7 (28th July, 2011)
Java SE 8 (18th March, 2014)
Overview of Java
Java is one of the programming language or technology used for developing
web applications. Java language developed at SUN Micro Systems in the year
1995 under the guidance of James Gosling and there team. Originally SUN
Micro Systems is one of the Academic university (Standford University
Network)
Whatever the software developed in the year 1990, SUN Micro Systems has
released on the name of oak, which is original name of java (scientifically oak
is one of the tree name). The OAK has taken 18 months to develop.
The oak is unable to fulfill all requirements of the industry. So James Gosling
again reviews this oak and released with the name of java in the year 1995.
Scientifically java is one of the coffee seed name.
Java divided into three categories, they are
J2SE (Java 2 Standard Edition)
J2EE (Java 2 Enterprise Edition)
J2ME (Java 2 Micro or Mobile Edition)
J2SE
J2SE is used for developing client side applications.
J2EE
J2EE is used for developing server side applications.
J2ME
J2ME is used for developing mobile or wireless application by making use of a
predefined protocol called WAP(wireless Access / Application protocol).
Features of Java
There is given many features of java. They are also known as java
buzzwords. The Java Features given below are simple and easy to
understand.
1.Simple
2.Object-Oriented
3.Platform independent
4.Secured
5.Robust
6.Architecture neutral
7.Portable
8.Dynamic
9.Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it
after C++).
removed many confusing and/or rarely-used features e.g.,
explicit pointers, operator overloading etc.
No need to remove unreferenced objects because there is
Automatic Garbage Collection in java.
Object-oriented
Object-oriented means we organize our software as a combination
of different types of objects that incorporates both data and
behaviour.
Object-oriented programming(OOPs) is a methodology that simplify
software development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Secured
Java is secured because:
o No explicit pointer
o Java Programs run inside virtual machine sandbox
Robust
Robust simply means strong. Java uses strong memory management.
There are lack of pointers that avoids security problem. There is
automatic garbage collection in java. There is exception handling and
type checking mechanism in java. All these points makes java robust.
Architecture-neutral
There is no implementation dependent features e.g. size of primitive
types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-
bit architecture and 4 bytes of memory for 64-bit architecture. But in
java, it occupies 4 bytes of memory for both 32 and 64 bit
architectures.
Portable
We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is
"close" to native code still somewhat slower than a compiled
language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used
for creating distributed applications. We may access files by calling
the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can
write Java programs that deal with many tasks at once by defining
multiple threads. The main advantage of multi-threading is that it
doesn't occupy memory for each thread. It shares a common memory
area. Threads are important for multi-media, Web applications etc.
Java is Robust because it is highly supported language. It is portable across
many Operating systems. Java also has feature of Automatic memory
management and garbage collection. Strong type checking mechanism
of Java also helps in makingJava Robust. Bugs, especially system crashing
bugs, are very rare in Java.
Java is considered as Portable because – Output of a Java compiler is Non
Executable Code i.e Bytecode. Bytecode is executed by Java run-time system,
which is called the Java Virtual Machine (JVM).
Java is considered as Dynamic because of Bytecode[a class file]. A source
code writen in one platform, the same code can be executed in any platform[
which JDK is installed.]. And it also loads the class files at runtime. anything that
happes at runtime is considered as Dynamic, so the java is.
To enable a Java application to execute anywhere on the network, the compiler
generates an architecture-neutral object file format--the compiled code is
executable on many processors, given the presence of the Java runtime
system. This is useful not only for networks but also for single system software
distribution.
C++ vs Java
There are many differences and similarities between C++
programming language and Java. A list of top differences between
C++ and Java are given below:
Comparison Index C++ Java
Platform- C++ is platform- Java is platform-independent.
independent dependent.
Mainly used C++ is mainly used for Java is mainly used for
for system programming. application programming. It is
widely used in window, web-
based, enterprise and mobile
applications.
Goto C++ supports goto Java doesn't support goto
statement. statement.
Multiple C++ supports multiple Java doesn't support multiple
inheritance inheritance. inheritance through class. It
can be achieved by interfaces
in java.
Operator C++ supports operator Java doesn't support operator
Overloading overloading. overloading.
Pointers C++ supports Java supports pointer
pointers. You can write internally. But you can't write
pointer program in the pointer program in java. It
C++. means java has restricted
pointer support in java.
Compiler and C++ uses compiler Java uses compiler and
Interpreter only. interpreter both.
Call by Value C++ supports both call Java supports call by value
and Call by by value and call by only. There is no call by
reference reference. reference in java.
Structure and C++ supports Java doesn't support structures
Union structures and unions. and unions.
Thread C++ doesn't have Java has built-in thread
Support built-in support for support.
threads. It relies on
third-party libraries for
thread support.
Documentation C++ doesn't support Java supports documentation
comment documentation comment (/** ... */) to create
comment. documentation for java source
code.
Virtual C++ supports virtual Java has no virtual keyword.
Keyword keyword so that we We can override all non-static
can decide whether or methods by default. In other
not override a words, non-static methods are
function. virtual by default.
unsigned right C++ doesn't support Java supports unsigned right
shift >>> >>> operator. shift >>> operator that fills
zero at the top for the negative
numbers. For positive
numbers, it works same like
>> operator.
Inheritance C++ creates a new Java uses single inheritance
Tree inheritance tree tree always because all classes
always. are the child of Object class in
java. Object class is the root of
inheritance tree in java.
What is JVM?
Java Virtual Machine (JVM) is a engine that provides runtime environment to
drive the Java Code or applications. It converts Java bytecode into machines
language. JVM is a part of Java Runtime Environment (JRE). In other
programming languages, the compiler produces machine code for a particular
system. However, Java compiler produces code for a Virtual Machine known as
Java Virtual Machine.
How JVM Works?
First, Java code is compiled into bytecode. This bytecode gets interpreted on
different machines
Between host system and Java source, Bytecode is an intermediary language.
JVM in Java is responsible for allocating memory space.
1) ClassLoader
The class loader is a subsystem used for loading class files. It performs three
major functions viz. Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant runtime
pool, and the code for methods.
3) Heap
All the Objects, their related instance variables, and arrays are stored in the
heap. This memory is common and shared across multiple threads.
4) JVM language Stacks
Java language Stacks store local variables, and it’s partial results. Each thread
has its own JVM stack, created simultaneously as the thread is created. A new
frame is created whenever a method is invoked, and it is deleted when method
invocation process is complete.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is
currently executing. In Java, each thread has its separate PC register.
6) Native Method Stacks
Native method stacks hold the instruction of native code depends on the native
library. It is written in another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems.
The test execution engine never carries any information about the tested
product.
8) Native Method interface
The Native Method Interface is a programming framework. It allows Java code
which is running in a JVM to call by libraries and native applications.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries(C, C++) which are needed
by the Execution Engine.
Software Code Compilation & Execution process
In order to write and execute a software program, you need the following
1) Editor – To type your program into, a notepad could be used for this
2) Compiler – To convert your high language program into native machine code
3) Linker – To combine different program files reference in your main program
together.
4) Loader – To load the files from your secondary storage device like Hard Disk,
Flash Drive, CD into RAM for execution. The loading is automatically done when
you execute your code.
5) Execution – Actual execution of the code which is handled by your OS &
processor.
With this background, refer the following video & learn the JVM internal working
and architecture of JVM (Java Virtual Machine).
What is Java Bytecode?
Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to
an assembler which is an alias representation of a C++ code. As soon as a java
program is compiled, java bytecode is generated. In more apt terms, java
bytecode is the machine code in the form of a .class file. With the help of java
bytecode we achieve platform independence in java.
How does it works?
When we write a program in Java, firstly, the compiler compiles that program
and a bytecode is generated for that piece of code. When we wish to run this
.class file on any other platform, we can do so. After the first compilation, the
bytecode generated is now run by the Java Virtual Machine and not the
processor in consideration. This essentially means that we only need to have
basic java installation on any platforms that we want to run our code on.
Resources required to run the bytecode are made available by theJava Virtual
Machine, which calls the processor to allocate the required resources. JVM's are
stack-based so they stack implementation to read the codes.
Garbage collection in Java is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java
Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are
created on the heap, which is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage collector finds these
unused objects and deletes them to free up memory.
What is Garbage Collection?
In C/C++, a programmer is responsible for both the creation and destruction of objects.
Usually, programmer neglects the destruction of useless objects. Due to this
negligence, at a certain point, sufficient memory may not be available to create new
objects, and the entire program will terminate abnormally, causing
OutOfMemoryErrors.
But in Java, the programmer need not care for all those objects which are no longer in
use. Garbage collector destroys these objects. The main objective of Garbage Collector
is to free heap memory by destroying unreachable objects. The garbage collector is the
best example of the Daemon thread as it is always running in the background.
How Does Garbage Collection in Java works?
Java garbage collection is an automatic process. Automatic garbage collection is the
process of looking at heap memory, identifying which objects are in use and which are
not, and deleting the unused objects. An in-use object, or a referenced object, means
that some part of your program still maintains a pointer to that object. An unused or
unreferenced object is no longer referenced by any part of your program. So the
memory used by an unreferenced object can be reclaimed. The programmer does not
need to mark objects to be deleted explicitly. The garbage collection implementation
lives in the JVM.
Variables and Data Types
Programs are often required to store information. For example, to write a
program that adds two numbers, we need to store the first number, the second
number and the result. This is accomplished by the use of variables. Variables
represent memory area where the information is stored. Following is the
physical representation of a variable:
A variable has a name, a value and a data type. A variable name is a symbolic
representation of the memory area in which the information would be stored.
The value is the actual data that is going to be stored. And a particular variable
can only store one type of information. It could either be an integer, a real
number, a single character or a String. This is specified by the data type.
In our example, we have a variable named firstNumber of type int and having a
value 3. The data
Range ( in
Data Range (inclusive of both
Size in bits exponential
type values)
notation)
byte 8 - 128 to 127 - 27 to 27-1
short 16 - 32 768 to 32 767 - 215 to 215 -1
- 2 147 483 648 to 2 147 483
int 32 - 231 to 231 -1
647
- 9 223 372 036 854 775 808
long 64 - 263 to 263 -1
to 9 223 372 036 854 775 807
float 32 -3.4*10-38 to 3.4*1038
-1.7*10-308 to
double 64
1.7*10308
char 16 0 to 65536
Not properly
boolean true and false
defined
naming conventions in java
By using standard Java naming conventions, you make your code
easier to read for yourself and for other programmers. Readability of
Java program is very important. It indicates that less time is spent to
figure out what the code does.
Name Convention
class should start with uppercase letter and be a noun e.g.
name String, Color, Button, System, Thread etc.
interface should start with uppercase letter and be an adjective e.g.
name Runnable, Remote, ActionListener etc.
method should start with lowercase letter and be a verb e.g.
name actionPerformed(), main(), print(), println() etc.
variable should start with lowercase letter e.g. firstName,
name orderNumber etc.
package should be in lowercase letter e.g. java, lang, sql, util etc.
name
constants should be in uppercase letter. e.g. RED, YELLOW,
name MAX_PRIORITY etc.
Called Logical OR
Operator. If any of the
two operands are non-
|| (logical or) (A || B) is true
zero, then the
condition becomes
true.
C >>= 2
is same
>>= Bitwise AND assignment operator.
as C = C
>> 2
C &= 2 is
Right shift AND assignment
&= same as C
operator.
=C&2
Array In Java
An array is used to store a group of values, all of which have the same data
type. All the elements stored in the arrays are accessed by simply using the
variable name and the index of the element
The following statements show the declaration of an array named a, which holds
int values.
int [] a;
The square brackets may also be placed at the end of the array name, as shown
below. It would make no difference.
int a[];
Just like variables, we may also declare more than one array in a single
statement, as shown below:
int[] a, b, c;
The new keyword returns a reference to the array being created which is then
assigned to an appropriate variable. The size of the arrays (or the length, which
is the number of elements the array will hold) is also specified. Following
statements creates an array to hold seven integers and assigns its reference to
eth arrays variable a.
a = new int[7];
As with variables, the declaration and initialisation of arrays can be combined
into s ingle statement as shown below:
int[] a = new int[7];
The following statements initialise some of the elements of the array a.
a[0]=3;
a[1]=34;
a[5]=7;
Elements accessed with the above notation ( a[index] ) may be used just like
normal variables. We may print those values, use them in calculations, pass
them as arguments and so on.
System.out.println( a[1] );
int sum = a[6] + a[5];
double root = Math.sqrt ( a[5] );
Processing Arrays using Loops
It would be quite difficult to process each of the array's elements individually as
we have done in the previous chapter. Since these are repetitive tasks,
repetition statements like for and while come to our rescue. The common
approach is to use a for loop with a variable used to keep track of the index
number and iterate through the entire array.
For example, the following code stores the numbers from 1 to 7 in a seven
element int array.
int[] a =new int[7];
for ( int i=0; i<a.length; i++) {
a[i]= i+1;
}
In a similar way, a for loop can be used to print the elements of the array.
for ( int i=0; i<a.length; i++) {
System.out.println("Element at index "+i+" is "+a[i]);
}
And the code below stores the first seven even numbers in the array a, starting
from 2.
for ( int i=0; i<a.length; i++) {
a[i] = (i+1) * 2;
}
Simple Example of for-each loop for traversing the array elements:
1.
2. class ForEachExample1{
3. public static void main(String args[]){
4. int arr[]={12,13,14,44};
5.
6. for(int i:arr){
7. System.out.println(i);
8. }
9.
10. }
11. }
Control Statement in Java
In Java, control statements can be divided into the following three categories:
Selection Statements
Iteration Statements
Jump Statements
Selection Statements
Selection statements allow you to control the flow of program execution on the
basis of the outcome of an expression or state of a variable known during
runtime.
Example
1.
2. import java.util.Scanner;
3.
4. public class IfDemo
5. {
6. public static void main(String[] args) {
7.
8. int age;
9. Scanner inputDevice = new Scanner(System.in);
10. System.out.print("Please enter Age: ");
11. age = inputDevice.nextInt();
12. if(age > 18)
13. System.out.println("above 18 ");
14. }
15.
16. }
Output:
Example
1.
2. import java.util.Scanner;
3.
4. public class IfElseDemo
5. {
6. public static void main( String[] args )
7. {
8. int age;
9. Scanner inputDevice = new Scanner( System.in );
10. System.out.print( "Please enter Age: " );
11. age = inputDevice.nextInt();
12. if ( age >= 18 )
13. System.out.println( "above 18 " );
14. else
15. System.out.println( "below 18" );
16. }
17. }
Output
This statement following the else keyword can be another if or if-else statement.
That would looks like this:
if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;
Whenever the condition is true, the associated statement will be executed and
the remaining conditions will be bypassed. If none of the conditions are true then
the else block will execute.
Example
1.
2. import java.util.Scanner;
3.
4. public class IfElseIfDemo
5. {
6. public static void main( String[] args )
7. {
8. int age;
9. Scanner inputDevice = new Scanner( System.in );
10. System.out.print( "Please enter Age: " );
11. age = inputDevice.nextInt();
12. if ( age >= 18 && age <=35 )
13. System.out.println( "between 18-35 " );
14. else if(age >35 && age <=60)
15. System.out.println("between 36-60");
16. else
17. System.out.println( "not matched" );
18. }
19. }
Output
The Switch Statements
Example
1.
2. import java.util.Scanner;
3.
4. public class SwitchDemo
5. {
6. public static void main( String[] args )
7. {
8. int age;
9. Scanner inputDevice = new Scanner( System.in );
10. System.out.print( "Please enter Age: " );
11. age = inputDevice.nextInt();
12. switch ( age )
13. {
14. case 18:
15. System.out.println( "age 18" );
16. break;
17. case 19:
18. System.out.println( "age 19" );
19. break;
20. default:
21. System.out.println( "not matched" );
22. break;
23. }
24. }
25. }
Output
An expression must be of a type of byte, short, int or char. Each of the values
specified in the case statement must be of a type compatible with the
expression. Duplicate case values are not allowed. The break statement is used
inside the switch to terminate a statement sequence. The break statement is
optional in the switch statement.
Iteration Statements
Repeating the same code fragment several times until a specified condition is
satisfied is called iteration. Iteration statements execute the same set of
instructions until a termination condition is met.
Example
1.
2. public class WhileDemo
3. {
4. public static void main( String[] args )
5. {
6. int i = 0;
7. while ( i < 5 )
8. {
9. System.out.println( "Value :: " + i );
10. i++;
11. }
12. }
13. }
Output
Example
1.
2. public class DoWhileDemo
3. {
4. public static void main( String[] args )
5. {
6. int i = 0;
7. do
8. {
9. System.out.println( "value :: " + i );
10. i++;
11. }
12. while ( i < 5);
13. }
14. }
Output
A for loop executes a statement (that is usually a block) as long as the boolean
condition evaluates to true. A for loop is a combination of the three elements
initialization statement, boolean expression and increment or decrement
statement.
Syntax:
The initialization block executes first before the loop starts. It is used to initialize
the loop variable.
The condition statement evaluates every time prior to when the statement (that
is usually be a block) executes, if the condition is true then only the statement
(that is usually a block) will execute.
The increment or decrement statement executes every time after the statement
(that is usually a block).
Example
1.
2. public class WhileDemo
3. {
4. public static void main( String[] args )
5. {
6. int i = 0;
7. while ( i < 5 )
8. {
9. System.out.println( "Value :: " + i );
10. i++;
11. }
12. }
13. }
Output
This was introduced in Java 5. This loop is basically used to traverse the array
or collection elements.
Example
1.
2. public class ForEachDemo
3. {
4. public static void main( String[] args )
5. {
6. int[] i =
7. { 1, 2, 3, 4, 5 };
8. for ( int j : i )
9. {
10. System.out.println( "value :: " + j );
11. }
12. }
13. }
Output
Jump Statements
The break statement immediately quits the current iteration and goes to the first
statement following the loop. Another form of break is used in the switch
statement.
Example
1.
2. public class UnLabeledBreakDemo
3. {
4. public static void main( String[] args )
5. {
6. for ( int var = 0; var < 5; var++ )
7. {
8. System.out.println( "Var is : " + var );
9. if ( var == 3 )
10. break;
11. }
12. }
13. }
Output
Labeled Break Statement: This is used for when we want to jump the program
control out of nested loops or multiple loops.
Example
1.
2. public class LabeledBreakDemo
3. {
4. public static void main( String[] args )
5. {
6. Outer: for ( int var1 = 0; var1 < 5; var1++ )
7. {
8. for ( int var2 = 1; var2 < 5; var2++ )
9. {
10. System.out.println( "var1:" + var1 + ",
var2:" + var2 );
11. if ( var1 == 3 )
12. break Outer;
13. }
14. }
15. }
16. }
Output
Continue Statement
The continue statement is used when you want to continue running the loop with
the next iteration and want to skip the rest of the statements of the body for the
current iteration.
Example
1.
2. public class UnlabeledContinueDemo
3. {
4. public static void main( String[] args )
5. {
6. for ( int var1 = 0; var1 < 4; var1++ )
7. {
8. for ( int var2 = 0; var2 < 4; var2++ )
9. {
10. if ( var2 == 2 )
11. continue;
12. System.out.println( "var1:" + var1 + ",
var2:" + var2 );
13. }
14. }
15. }
16. }
Example
Labeled Continue Statement: This statement skips the current iteration of the
loop with the specified label.
Example
public class LabeledContinueDemo
{
public static void main( String[] args )
{
Outer: for ( int var1 = 0; var1 < 5; var1++ )
{
for ( int var2 = 0; var2 < 5; var2++ )
{
if ( var2 == 2 )
continue Outer;
System.out.println( "var1:" + var1 + ", var2:"
+ var2 );
}
}
}
}
Output
Return Statement
The return statement is used to immediately quit the current method and return
to the calling method. It is mandatory to use a return statement for non-void
methods to return a value.
Example
public class ReturnDemo
{
public static void main( String[] args )
{
ReturnDemo returnDemo = new ReturnDemo();
System.out.println( "No : " + returnDemo.returnCall()
);
}
int returnCall()
{
return 5;
}
}
Recursion in Java
Recursion in java is a process in which a method calls itself
continuously. A method in java that calls itself is called recursive
method.
Java Recursion Example 1: Infinite times
public class RecursionExample1 {
static void p(){
System.out.println("hello");
p();
}
Encapsulation
Binding (or wrapping) code and data together into a single
unit is known as encapsulation. For example: capsule, it is
wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully
encapsulated class because all the data members are private here.
Constructor in Java
Constructor in java is a special type of method that is used to
initialize the object.
Java constructor is invoked at the time of object creation. It
constructs the values i.e. provides data for the object that is why it is
known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all
the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes
that are built upon existing classes. When you inherit from an existing
class, you can reuse methods and fields of parent class, and you can
add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-
child relationship.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be
achieved).
o For Code Reusability.
Syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
The extends keyword indicates that you are making a new class
that derives from an existing class. The meaning of "extends" is to
increase the functionality.
In the terminology of Java, a class which is inherited is called parent
or super class and the new class is called child or subclass.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported
through interface only. We will learn about interfaces later.
Note: Multiple inheritance is not supported in java through class.
s1.display();
s2.display();
3. }
4. }
Test it Now
Output:111 Karan ITS
222 Aryan ITS
next →← prev
this keyword in java
There can be a lot of usage of java this keyword. In java, this is
a reference variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the
method.
Suggestion: If you are beginner to java, lookup only three usage
of this keyword.
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables and
parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the
example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
1. }}
Test it Now
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance
variables are same. So, we are using this keyword to distinguish
local variable and instance variable.
Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
1. }}
Test it Now
Output:
111 ankit 5000
112 sumit 6000
Types of Exception
There are mainly two types of exceptions: checked and unchecked
where error is considered as unchecked exception. The sun
microsystem says there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
15:35
VIDEO LINKS
PlayList Link:
https://www.youtube.com/playlist?list=PLV_K8gHBuQuIJ-
lf8XWHRHd_8sPUJo9a0
Lecture 1:Java vs C++, Bytecode,Why Java is platform Independent?JAVA Tutorial for Beginners
Punjabi
CJ Singh Vlogs
Lecture 1.5: Keywords, Variables, Constant, Data Types, Operators, JAVA Tutorial for Beginners
CJ Singh Vlogs
Lecture 2:First Program In Java, How we can execute Java program?Java For Beginners in Punjabi.
CJ Singh Vlogs
•
Lecture 3: Java Installation And Path Setting. Java not recognized as internal or external command
CJ Singh Vlogs
Lecture 4: Java Command Line Arguments, Scanner Class, BufferedReader Class, Java In Punjabi
CJ Singh Vlogs
Lecture 5: Java Conditional Statements, if, else, if else, nested if,switch case,Java In Punjabi
CJ Singh Vlogs
Lecture 6: Java Loops/Iterative Statements while, do while, for loop , Java In Punjabi with subtitle
CJ Singh Vlogs
Lecture 9: Java , Array, Jagged Array, Labeled Break and Continue Learn in Punjabi.
CJ Singh Vlogs
Lecture 10: Java Class, Method with arguments Learn Java In Punjabi subtitle in English
CJ Singh Vlogs
Lecture 11: Java Constructor, Method Overloading, Constructor Overloading, Learn Java In Punjabi.
CJ Singh Vlogs
Lecture 12: Inheritance in Java, Constructor under inheritance, Super , Learn Java In Punjabi.
CJ Singh Vlogs
Lecture 13: Method Overriding, Final Variable, Final Method, Final Class, Abstract Method & Class.
CJ Singh Vlogs
Lecture 14:Static Keyword, Static Variable, Static Method, Static Block. ਜਾਵਾ ਪੰਜਾਬੀ ਭਾਸਾ ਵਵਚ ਵ ਿੱਖੋ
CJ Singh Vlogs
Lecture 15: Interface In Java, Multiple inheritance in java. ਜਾਵਾ ਪੰਜਾਬੀ ਭਾਸਾ ਵਵਚ ਵ ਿੱਖੋ
CJ Singh Vlogs
Lecture 16: Packages In Java, Public , private, Projected, Default access specifier of Java.
CJ Singh Vlogs
Lecture 17: Exception Handling in JAVA, try, catch, finally block, multiple catch and nested try
CJ Singh Vlogs
Lecture 18: User define Exception, Extend Exception Class, Creating subclass of Exception Class.
CJ Singh Vlogs
Lecture 19: String and StringBuffer Class in Java. Methods and Differnece of String and StringBuffer
CJ Singh Vlogs
Lecture 20: Multithreading in JAVA, Thread Class, Runnable Interface, Life Cycle of a Thread.
CJ Singh Vlogs
Lecture 21: yield(), sleep(), stop() methods in Multithreading in JAVA, synchronized method in Java
CJ Singh Vlogs
Lecture 22: File Handling in Java, File, FileReader, FileWriter, FileOutputstream, FileInputstream
CJ Singh Vlogs
Lecture 23: Applet in java, Appletviewer, Applet Life cycle of an applet, Applet tag.
CJ Singh Vlogs
Lecture 24: Graphics in Applet, Animation in java, drawRect, drawArc, drawOval, image in Applet.
CJ Singh Vlogs
Lecture 25: Frame in Java,Layout Manager, Grid Layout, Flow layout, Border layout, Null layout.
CJ Singh Vlogs
Lecture 26: Event handling in java , Action Listener, Event on Button Click, actionPerformed in Java
CJ Singh Vlogs
Lecture 28: KeyListener, MouseListener, MouseMotionListener Keyboard and mouse listener in java
CJ Singh Vlogs