Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PDC - Cs Department Java Programming Sae4A

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

PDC – CS Department Java Programming SAE4A

Unit 1: Life Cycle-Graphics Programming-Managing Input/Output Files: Concept of

Introduction to Java-Features of Java-Basic Concepts of Object Oriented Streams-Stream Classes-Byte Stream Classes-Character Stream Classes – Using
Programming-Java Tokens-Java Statements-Constants-Variables-Data Types- Streams-Using the File Class-Creation of Files-Random Access Files-Other
Type Casting-Operators-Expressions-Control Statements: Branching and Stream Classes.
Looping Statements.
Unit-5:
Unit-2: Network basics –socket programming – proxy servers – TCP/IP – Net Address –
Classes, Objects and Methods-Constructors-Methods Overloading-Inheritance- URL – Datagrams -Java Utility Classes-Introducing the AWT: Working with
Overriding Methods-Finalizer and Abstract Methods-Visibility Control –Arrays, Windows, Graphics and Text- AWT Classes- Working with Frames-Working
Strings and Vectors-String Buffer Class-Wrapper Classes. with Graphics-Working with Color-Working with Fonts-Using AWT Controls,
Layout Managers and Menus.

Unit 3:
Interfaces-Packages-Creating Packages-Accessing a Package-Multithreaded
Programming-Creating Threads-Stopping and Blocking a Thread-Life Cycle of a
Thread-Using Thread Methods-Thread Priority-Synchronization-Implementing
the Runnable Interface
Unit-4:
Managing Errors and Exceptions-Syntax of Exception Handling Code-Using
Finally Statement-Throwing Our Own Exceptions-Applet Programming-Applet

Prepared by : S.P.Chitra Preetha Page 1


PDC – CS Department Java Programming SAE4A

UNIT 2 Steps to Compile and Run your first Java program


CLASS Step 1: Open a text editor and write the code as above.
Step 2: Save the file as Hello.java

First Java Program Step 3: Open command prompt and go to the directory where you saved your first
java program assuming it is saved in C:\
Let us look at a simple java program.
Step 4: Type javac Hello.java and press Return to compile your code. This
class Hello
command will call the Java Compiler asking it to compile the specified file. If there
{ are no errors in the code the command prompt will take you to the next line.
public static void main(String[] args) Step 5: Now type java Hello on command prompt to run your program.
{ Step 6: You will be able to see Hello world program printed on your command
System.out.println ("Hello World program"); prompt.
}

class : class keyword is used to declare classes in Java Now let us see What happens at Runtime
public : It is an access specifier. Public means this function is visible to all. After writing your Java program, when you will try to compile it. Compiler will
static : static is again a keyword used to make a function static. To execute a static perform some compilation operation on your program.
function you do not have to create an Object of the class. The main() method here Once it is compiled successfully byte code(.class file) is generated by the compiler.
is called by JVM, without creating any object for class.
void : It is the return type, meaning this function will not return anything.
main : main() method is the most important method in a Java program. This is the
method which is executed, hence all the logic must be inside the main() method. If a
java class is not having a main() method, it causes compilation error.
System.out.println : This is used to print anything on the console like printf in C
language.

Prepared by : S.P.Chitra Preetha Page 2


PDC – CS Department Java Programming SAE4A

After compiling when you will try to run the byte code(.class file), the following steps
are performed at runtime:-

1. Class loader loads the java class. It is subsystem of JVM Java Virtual machine.

2. Byte Code verifier checks the code fragments for illegal codes that can violate

access right to the object.

3. Interpreter reads the byte code stream and then executes the instructions, step

by step.

Definition: A class is a collection of objects of similar type. Once a class is


defined, any number of objects can be produced which belong to that class.
A class is declared using class keyword. A class contain both data and code that
operate on that data. The data or variables defined within a class are
called instance variables and the code that operates on this data is known
as methods.

Rules for Java Class

• A class can have only public or default(no modifier) access specifier.

• It can be either abstract, final or concrete (normal class).

• It must have the class keyword, and class must be followed by a legal identifier.

Prepared by : S.P.Chitra Preetha Page 3


PDC – CS Department Java Programming SAE4A

void display()
• It may optionally extend one parent class. By default, it will extend
{
java.lang.Object.

• It may optionally implement any number of comma-separated interfaces. System.out.println(“hai”);

• The class's variables and methods are declared within a set of curly braces {}. }
• Each .java source file may contain only one public class. A source file may }
contain any number of default visible classes.

• Finally, the source file name must match the public class name and it must have
OBJECTS
a .java suffix.

Objects are instances of the Class. Classes and Objects are very much related to
Class Declaration each other. Without objects you can't use a class.
class classname
{ Syntax
… variables;
Classname objectname = new classname();
Methods;
Myclass obj1 = new obj1();
…}
Accessing an object
Example
Dot operator is used to access the variable and methods of a class.
class myclass
Syntax
{
Object name . variablename;
Int a,b;

Prepared by : S.P.Chitra Preetha Page 4


PDC – CS Department Java Programming SAE4A

Objectname.methodname(); name=name+st;

return name;
Example }

Obj1.a;

Obj1.add();

Methods

A Java method is a collection of statements that are grouped together to perform


an operation.

Methods in Java
Method describe behavior of an object. A method is a collection of statements that
are group together to perform an operation.
Syntax :
return-type methodName(parameter-list) Modifier : Modifier are access type of method. We will discuss it in detail later.
{
Return Type : A method may return value. Data type of value return by a method is
//body of method declare in method heading.
} Method name : Actual name of the method.
Parameter : Value passed to a method.
Method body : collection of statement that defines what method does.
Example of a Method
public String getName(String st)

String name="StudyTonight";

Prepared by : S.P.Chitra Preetha Page 5


PDC – CS Department Java Programming SAE4A

Parameter Vs. Argument


1. call-by-value : In this approach copy of an argument value is pass to a method.
While talking about method, it is important to know the difference between two
terms parameter and argument. Changes made to the argument value inside the method will have no effect on

Parameter is variable defined by a method that receives value when the method is the arguments.
called. Parameter are always local to the method they dont have scope outside the
method. While argument is a value that is passed to a method when it is called. 2. call-by-reference : In this reference of an argument is pass to a method. Any

changes made inside the method will affect the agrument value.

NOTE : In Java, when you pass a primitive type to a method it is passed by value
whereas when you pass an object of any type to a method it is passed as reference.

Example of call-by-value
public class Test

public void callByValue(int x)

x=100;

public static void main(String[] args)

int x=50;

Test t = new Test();

t.callByValue(x); //function call

System.out.println(x);
call-by-value and call-by-reference
}
There are two ways to pass an argument to a method

Prepared by : S.P.Chitra Preetha Page 6


PDC – CS Department Java Programming SAE4A

} Output :
Output : Before 10 20

50 After 100 50

Methods with parameters


Example of call-by-reference
Following program shows the method with passing parameter.
public class Test

int x=10;
class prg
int y=20; {
public void callByReference(Test t) int a,b,sum1;
{
public void take(int x,int y)
t.x=100;
{
t.y=50;

}
a=x;
public static void main(String[] args) b=y;
{ }
public void sum()
Test ts = new Test();
{
System.out.println("Before "+ts.x+" "+ts.y);
sum1=a+b;
ts.callByReference(ts);

System.out.println("After "+ts.x+" "+ts.y); }


} public void print()
{

Prepared by : S.P.Chitra Preetha Page 7


PDC – CS Department Java Programming SAE4A

System.out.println("The Sum is"+sum); }


} public void sum()
} {
class prg1 sum1=a+b;
{ return(sum1);
public static void main(String args[]) }
{ }
prg obj=new prg(); class prg1
obj.take(10,15); {
obj.sum(); public static void main(String args[])
obj.print(); {
} prg obj=new prg();
} obj.take(10,15);
Methods with a Return Type int res = obj.sum();
When method return some value that is the type of that method. System.out.println("The Sum is"+res);
class prg }
{ }
int a,b,sum1;
public void take(int x,int y)
{ Method Overloading
a=x; Method overloading means method name will be same but each method should be
b=y; different parameter list.
Prepared by : S.P.Chitra Preetha Page 8
PDC – CS Department Java Programming SAE4A

class prg1 }
{ class Demo
int x=5,y=5,z=0; {
public void sum() public static void main(String args[])
{ {
z=x+y; prg1 obj=new prg1();
System.out.println("Sum is "+z);
obj.sum();
} obj.sum(10,12);
public void sum(int a,int b) System.out.println(+obj.sum(15));
{ }
x=a; }
y=b; Output:
z=x+y; sum is 10
System.out.println("Sum is "+z); sum is 22
} 27
public int sum(int a)
Passing Objects as Parameters
{
Objects can even be passed as parameters.
x=a;
class para
z=x+y;
{
return z;
int n,n2,mul;
}
public void take(int x,int y)

Prepared by : S.P.Chitra Preetha Page 9


PDC – CS Department Java Programming SAE4A

{ ob.take2(ob);
n=x; ob.multi();
n2=y; }
} }
Output:
public void take2(para obj)
C:\cc>javac DemoPara.java
{
C:\cc>java DemoPara
n=obj.n;
n2=obj.n2;
Product is21
}
public void multi()
Constructor
{
Constructor in java is a special type of method that is used to initialize the
mul=n*n2;
object.
System.out.println("Product is"+mul);
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.
}
class DemoPara
Rules for creating java constructor
{
public static void main(String args[]) There are basically two rules defined for the constructor.

{
1. Constructor name must be same as its class name
para ob=new para();
2. Constructor must have no explicit return type
ob.take(3,7);

Prepared by : S.P.Chitra Preetha Page 10


PDC – CS Department Java Programming SAE4A

class Car
1. EXAMPLE FOR DEFAULT CONSTRUCTOR
{
2. class Student{
String name ;
3. int id;
String model;
4. Student ()
Car( ) //Constructor
5. {
{
6. id = 10;
name ="";
7. }
model="";
8. void display()
}
9. {
}
10. System.out.println(id);

Types of java constructors 11. }


12. public static void main(String args[]){
There are two types of constructors: 13. Student s1=new Student();
14. s1.display();
1. Default constructor (no-arg constructor)
15. }
2. Parameterized constructor 16. }
17. EXAMPLE FOR PARAMETERIZED CONSTRUCTOR
18. class Student{
19. int id;
20. Student ( int a)
21. {
22. id = a;
23. }
ar c = new Car() //Default constructor invoked 24. void display()
Car c = new Car(name); //Parameterized constructor invoked 25. {
26. System.out.println(id);
Prepared by : S.P.Chitra Preetha Page 11
PDC – CS Department Java Programming SAE4A

} Student5(int i,String n,int a)


public static void main(String args[]){ { {
Student s1=new Student(10); 1. id = i;
s1.display(); 2. name = n;
} 3. age=a;
4. }
}
5. void display()
Constructor Overloading 6. {
7. System.out.println(id+" "+name+" "+age);
8. }
Constructor overloading is a technique in Java in which a class can have
9.
any number of constructors that differ in parameter lists.The compiler
10. public static void main(String args[]){
differentiates these constructors by taking into account the number of
11. Student5 s1 = new Student5(111,"Karan");
parameters in the list and their type. 12. Student5 s2 = new Student5(222,"Aryan",25);
13. s1.display();

Example of Constructor Overloading 14. s2.display();


15. }
class Student5{
16. }
int id;
String name;
this keyword
int age;
Student5(int i,String n)
• this keyword is used to refer to current object.
{
id = i; • this is always a reference to the object on which method was invoked.
name = n; • this can be used to invoke current class constructor.
}
• this can be passed as an argument to another method.
Prepared by : S.P.Chitra Preetha Page 12
PDC – CS Department Java Programming SAE4A

Example : }

class Box }

Double width, weight, dept;

Box (double w, double h, double d) The this is also used to call Method of that class.
{ public void getName()
this.width = w; {
this.height = h;
System.out.println("Studytonight");
this.depth = d;
}
}

}
public void display()
Here the this is used to initialize member of current object. {

this.getName();

System.out.println();

}
The this is used to call overloaded constructor in java
class Car

private String name; this is used to return current Object


public Car() public Car getCar()

{ {

this("BMW"); //oveloaded constructor is called. return this;

} }

public Car(String n)

this.name=n; //member is initialized using this.

Prepared by : S.P.Chitra Preetha Page 13


PDC – CS Department Java Programming SAE4A

Garbage Collection Access Modifiers in java


In Java destruction of object from memory is done automatically by the JVM. When
There are two types of modifiers in java: access modifiers and non-access
there is no reference to an object, then that object is assumed to be no longer
modifiers.
needed and the memory occupied by the object are released. This technique is
called Garbage Collection. This is accomplished by the JVM.
The access modifiers in java specifies accessibility (scope) of a data member,
Advantages of Garbage Collection method, constructor or class.

There are 4 types of java access modifiers:


1. Programmer doesn't need to worry about dereferencing an object.

2. It is done automatically by JVM. 1. private

2. default
3. Increases memory efficiency and decreases the chances for memory leak.
3. protected

4. public

finalize() method There are many non-access modifiers such as static, abstract, synchronized,
native, volatile, transient etc. Here, we will learn access modifiers.
Sometime an object will need to perform some specific task before it is destroyed
such as closing an open connection or releasing any resources held. To handle
such situation finalize() method is used. finalize() method is called by garbage
collection thread before collecting object. Its the last chance for any object to
1) private access modifier
perform cleanup utility. The private access modifier is accessible only within class.
Signature of finalize() method
1. class A{
protected void finalize()
2. private int data=40;
{
3. private void msg(){System.out.println("Hello java");}
//finalize-code
4. }
}

Prepared by : S.P.Chitra Preetha Page 14


PDC – CS Department Java Programming SAE4A

2) default access modifier


If you don't use any modifier, it is treated as default bydefault. The
default modifier is accessible only within package.

package pack;
class A{
void msg(){System.out.println("Hello");}
}
Abstract class
3) protected access modifier If a class contain any abstract method then the class is declared as abstract class.
An abstract class is never instantiated. It is used to provide abstraction. Although it
The protected access modifier is accessible within package and outside the does not provide 100% abstraction because it can also have concrete method.
package but through inheritance only. Syntax :
abstract class class_name { }
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
} Abstract method
Method that are declared without any body within an abstract class are
4) public access modifier called abstract method. The method body will be defined by its subclass. Abstract
method can never be final and static. Any class that extends an abstract class must
The public access modifier is accessible everywhere. It has the widest implement all the abstract methods declared by the super class.
scope among all other modifiers.
Syntax :
abstract return_type function_name (); // No definition
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

Prepared by : S.P.Chitra Preetha Page 15


PDC – CS Department Java Programming SAE4A

{
Example of Abstract class
abstract void callme();
abstract class A
public void normal()
{
{
abstract void callme();
System.out.println("this is concrete method");
}
}
class B extends A
}
{
class B extends A
void callme()
{
{
void callme()
System.out.println("this is callme.");
{
}
System.out.println("this is callme.");
public static void main(String[] args)
}
{
public static void main(String[] args)
B b = new B();
{
b.callme();
B b = new B();
}
b.callme();
}
b.normal();
Output :
}
this is callme.
}

Output :

Abstract class with concrete(normal) method. this is callme.


Abstract classes can also have normal methods with definitions, along with abstract this is concrete method.
methods.
abstract class A

Prepared by : S.P.Chitra Preetha Page 16


PDC – CS Department Java Programming SAE4A

Points to Remember Example :


int[ ] arr;

char[ ] arr;
1. Abstract classes are not Interfaces. They are different, we will study this when
short[ ] arr;
we will study Interfaces.
long[ ] arr;
2. An abstract class may or may not have an abstract method. But if any class has int[ ][ ] arr; // two dimensional array.

even a single abstract method, then it must be declared abstract.

3. Abstract classes can have Constructors, Member variables and Normal

methods. Initialization of Array


new operator is used to initialize an array.
4. Abstract classes are never instantiated.
Example :
5. When you extend Abstract class with abstract method, you must define the
int[ ] arr = new int[10]; //10 is the size of array.
abstract method in the child class, or make the child class abstract. or

int[ ] arr = {10,20,30,40,50};

Concept of Array in Java


An array is a collection of similar data types. Array is a container object that hold
values of homogenous type. It is also known as static data structure because size of
an array must be specified Accessing array element
As mention ealier array index starts from 0. To access nth element of an array.
Array Declaration Syntax
Syntax : arrayname[n-1];
datatype[ ] identifier;
Example : To access 4th element of a given array
or
int[ ] arr = {10,20,30,40};
datatype identifier[ ];
System.out.println("Element at 4th place" + arr[3]);
Both are valid syntax for array declaration. But the former is more readable.
The above code will print the 4th element of array arr on console.

Prepared by : S.P.Chitra Preetha Page 17


PDC – CS Department Java Programming SAE4A

rrrrrrrrrrrrrrrrrrclass Test

public static void main(String[] args)

int[] arr = {10, 20, 30, 40};

for(int x : arr)

System.out.println(x);

Output :
10

20

30

40

Prepared by : S.P.Chitra Preetha Page 18

You might also like