You are on page 1of 25

Week 1. Use Eclipse or Net bean platform and acquaint with the various menus.

Create a test
project, add a test class, and run it. See how you can use auto suggestions, auto fill.
Try code formatter and code refactoring like renaming variables, methods, and
classes. Try debug step by step with a small program of about 10 to 15 lines which
contains at least one if else condition and a for loop.

Program :

import java.util.*;
public class TestProject
{
public static void main(String[] args)
{
System.out.println("Welcome to Bharat Institute Of Engineering & Technology");
Scanner sc = new Scanner(System.in);
System.out.println("Enter valid Number");
int n = sc.nextInt();
int c = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
c++;
}
}
if (c == 2)
{
System.out.println(n + "is Prime Number");
}
else
{
System.out.println(n + "is not Prime Number");
}
}
}

2)Control Flow Statements Program

i)if
Syntax:

if(condition){
//code to be executed
}

Example:

public class IfExample {


public static void main(String[] args) {
int age=20;
if(age>18){
System.out.print("Age is greater than 18");
}
}
}

Output:

Age is greater than 18

ii) Syntax:

1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }

Example:

1. public class IfElseExample {


2. public static void main(String[] args) {
3. int number=13;
4. if(number%2==0){
5. System.out.println("even number");
6. }else{
7. System.out.println("odd number");
8. }
9. }
10. }

iii) Syntax:

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

Example:

1. public class SwitchExample {


2. public static void main(String[] args) {
3. int number=20;
4. switch(number){
5. case 10: System.out.println("10");
6. break;
7. case 20: System.out.println("20");
8. break;
9. case 30: System.out.println("30");
10. break;
11. default:System.out.println("Not in 10, 20 or 30");
12. }
13. }
14. }

Output:

20
iv) For loop

Syntax:

1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
4. public class ForExample {
5. public static void main(String[] args) {
6. for(int i=1;i<=10;i++){
7. System.out.println(i);
8. }
9. }
10. }

Output:

1
2
3
4
5

v)foreach loop

syntax :

for(datatype variablename:array or collection)

Example program :

Public class Foreachloopexample

Public static void main(String args[])


{

Int arr[]={10,12,15,12};

for(int i:arr)

System.out.println(i);

1. vi) while loop


2. while(condition){
3. //code to be executed
4. }

Example:

1. public class WhileExample {


2. public static void main(String[] args) {
3. int i=1;
4. while(i<=10){
5. System.out.println(i);
6. i++;
7. }
8. }
9. }

Output:

1
2
3
4
5
6
7
8
9
10

vii) do while loop

Syntax:

1. do{
2. //code to be executed
3. }while(condition);

Example:

1. public class DoWhileExample {


2. public static void main(String[] args) {
3. int i=1;
4. do{
5. System.out.println(i);
6. i++;
7. }while(i<=10);
8. }
9. }

Output:

1
2
3
4
5
6
7
8
9
10

viii) break statement

Java Break Statement with Loop

Example:
1. public class BreakExample {
2. public static void main(String[] args) {
3. for(int i=1;i<=10;i++){
4. if(i==5){
5. break;
6. }
7. System.out.println(i);
8. }
9. }
10. }

Output:

1
2
3
4

ix) Java Continue Statement Example

Example:

1. public class ContinueExample {


2. public static void main(String[] args) {
3. for(int i=1;i<=10;i++){
4. if(i==5){
5. continue;
6. }
7. System.out.println(i);
8. }
9. }
10. }

Output:

1
2
3
4
6
7
8
9
10

3)Constructor program

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.

1. class Bike1{
2. Bike1(){System.out.println("Bike is created");}
3. public static void main(String args[]){
4. Bike1 b=new Bike1();
5. }
6. }

Output:

Bike is created

Example of default constructor that displays the default values


1. class Student3{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. s1.display();
11. s2.display();
12. }
13. }

Output:
0 null
0 null

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

1. class Student4{
2. int id;
3. String name;
4.
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student4 s1 = new Student4(111,"Karan");
13. Student4 s2 = new Student4(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }
Test it Now

Output:

111 Karan
222 Aryan

4)METHOD OVERLOADING AND OVER-RIDING

Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}

Output:

22
33

Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
Test it Now

Output:

22
24.9
Example of method overriding
In this example, we have defined the run method in the subclass as defined in the parent
class but it has some specific implementation. The name and parameter of the method is
same and there is IS-A relationship between the classes, so there is method overriding.

1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }
Test it Now

Output:Bike is running safely

5)TYPE CASTING PROGRAM

Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;

byte y = (byte)x;

In Java, type casting is classified into two types,

• Widening Casting(Implicit)
• Narrowing Casting(Explicitly done)

Widening or Automatic type converion


Automatic Type casting take place when,

• the two types are compatible


• the target type is larger than the source type

Example :
public class Test

public static void main(String[] args)

int i = 100;

long l = i; //no explicit type casting required

float f = l; //no explicit type casting required

System.out.println("Int value "+i);

System.out.println("Long value "+l);

System.out.println("Float value "+f);

}
}

Output :
Int value 100

Long value 100

Float value 100.0

Narrowing or Explicit type conversion


When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.
Example :
public class Test

public static void main(String[] args)

double d = 100.04;

long l = (long)d; //explicit type casting required

int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);

System.out.println("Long value "+l);

System.out.println("Int value "+i);

Output :
Double value 100.04

Long value 100

Int value 100

----------------------------------------------------------------------------------------------------------------------------- -------------

6) FACTORIAL PROGRAM
Factorial Program using loop in java
Let's see the factorial Program using loop in java.

1. class FactorialExample{
2. public static void main(String args[]){
3. int i,fact=1;
4. int number=5;//It is the number to calculate factorial
5. for(i=1;i<=number;i++){
6. fact=fact*i;
7. }
8. System.out.println("Factorial of "+number+" is: "+fact);
9. }
10. }

Output:

Factorial of 5 is: 120

Factorial Program using recursion in java


Let's see the factorial program in java using recursion.

1. class FactorialExample2{
2. static int factorial(int n){
3. if (n == 0)
4. return 1;
5. else
6. return(n * factorial(n-1));
7. }
8. public static void main(String args[]){
9. int i,fact=1;
10. int number=4;//It is the number to calculate factorial
11. fact = factorial(number);
12. System.out.println("Factorial of "+number+" is: "+fact);
13. }
14. }

Output:
Factorial of 4 is: 24

7)INHERITANCE PROGRAMS

Syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

Single Inheritance Example


File: TestInheritance.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating...

Multilevel Inheritance Example


File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:

meowing...
eating...

8)ABSTRACT CLASS,INTERFACE,PACKAGES

Abstract class in Java


A class that is declared as abstract is known as abstract class. It needs to be extended
and its method implemented. It cannot be instantiated.

Example abstract class


1. abstract class A{}

abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.

Example abstract method


1. abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method


In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

EX1

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely..");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
OUTPUT

running safely..

EX 2

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape
() method
15. s.draw();
16. }
17. }
OUTPUTTO
OOest OOit Now
drawing circle

Java Interface Example


In this example, Printable interface has only one method, its implementation is provided in
the A class.
EX 1

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Test it Now

Output:

Hello

EX2

Java Interface Example: Drawable


In this example, Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In real scenario, interface is defined by someone but
implementation is provided by different implementation providers. And, it is used by
someone else. The implementation part is hidden by the user which uses the interface.

File: TestInterface1.java

1. //Interface declaration: by first user


2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable
()
16. d.draw();
17. }}
Test it Now

Output:

drawing circle

Simple example of java package


The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package accessible
to the current package.

Example of package that import the packagename.*


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import fully qualified name


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
Output:Hello

9)SERIALIZATION AND DESERIALIZATION

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

Example of Java Serialization


In this example, we are going to serialize the object of Student class. The writeObject()
method of ObjectOutputStream class provides the functionality to serialize the object. We
are saving the state of the object in the file named f.txt.

1. import java.io.*;
2. class Persist{
3. public static void main(String args[])throws Exception{
4. Student s1 =new Student(211,"ravi");
5.
6. FileOutputStream fout=new FileOutputStream("f.txt");
7. ObjectOutputStream out=new ObjectOutputStream(fout);
8.
9. out.writeObject(s1);
10. out.flush();
11. System.out.println("success");
12. }
13. }
success

Example of Java Deserialization


1. import java.io.*;
2. class Depersist{
3. public static void main(String args[])throws Exception{
4.
5. ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
6. Student s=(Student)in.readObject();
7. System.out.println(s.id+" "+s.name);
8.
9. in.close();
10. }
11. }
OUTPUT
211 ravi

10)ENUMERATION PROGRAM

Java Enum
Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc.
The java enum constants are static and final implicitly. It is available from JDK 1.5.

Java Enums can be thought of as classes that have fixed set of constants.

Points to remember for Java Enum


o enum improves type safety

o enum can be easily used in switch

o enum can be traversed

o enum can have fields, constructors and methods

o enum may implement many interfaces but cannot extend any class because it
internally extends Enum class

Simple example of java enum


1. class EnumExample1
2. {
3. public enum Season { WINTER, SPRING, SUMMER, FALL }
4.
5. public static void main(String[] args)
6. {
7. for (Season s : Season.values())
8. {
9. System.out.println(s);
10. }
11.
12. }
13. }
Test it Now

Output:WINTER
SPRING
SUMMER
FALL

You might also like