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

Unit - 3 Java Programming class 12

JAVA PROGRAMMING CODE CLASS 12 FREE PDF

Uploaded by

k7samir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Unit - 3 Java Programming class 12

JAVA PROGRAMMING CODE CLASS 12 FREE PDF

Uploaded by

k7samir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CLASS : XII Part - B Information Technology (802)

UNIT – 3
Java Programming

IDE
IDE stands for Integrated Development Environment. It facilitates application development and
provides a central interface with all the tools like editor, debugger, compiler etc.

Netbeans IDE
It is a free, open source IDE which helps us to develop desktop, mobile and web applications. It
provides GUI components for building the applications in Java using drag and drop features.

Frame

Components of Netbeans IDE


Title Bar : It is the top most area of the IDE which displays title of the project on left side and
maximize, minimize & restore button on the right side.
Menu Bar : It is situated below the title bar. It has several menus like File, Edit, View etc.
Tool Bar : It is available below the menu bar. It has shortcut icon of several commands of
different menus.
GUI Builder : It is an area where components are placed. There are two views of GUI builder :
Design view and Source view.

Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 1 of 17
CLASS : XII Part - B Information Technology (802)

Palette : It is a window which contains different types of control or components for designing GUI
applications.
Inspector window : It displays hierarchy of all the components placed on the current form. It
displays non-visible components also such as timer, data source etc.
Properties window : It displays all properties of selected controls on the form. We can change
the properties also here.
Code Editor Window : It is an area where we type the program or source code of Java
applications. It appears when we double click the control or by clicking Source tab.
Project Window : It displays list of all projects and files.

Components / Controls
It is a basic element of interface for designing an application such as jLabel, jButton, jTextField
etc. It is also known as widget. There are two types of controls :
(i) Parent or Container control : Controls that contain other controls are known as parent
or container control. It acts as a base or background for other controls. When we move
parent control then all its child controls move along with it. Example : jFrame, jPanel etc.
(ii) Child control : The control which is placed on container control is known as child
control. Example : jLabel, jTextField, jButton etc.

Properties
Properties of an object or control is used to define its characteristics. It is used to change the
appearance of control on the form. Example : Text, Font etc.

Methods
It is the behavior of an object or control. It is used to perform some actions on the control.
Example : setText( ), getText( ) etc.

Events
Change in the state of an object or control is known as event. It describes the actions which are
performed on objects. It is generated when a user interacts with the GUI components. Example :
actionPerformed, moveMouse, keyPressed.

Class
It is a user defined data type. It is used to combine data and methods in a single unit. Concept of
OOPs is implemented in the programming by using class keyword.

Object
An instance of a class is known as object. Members of a class can be accessed with the help of
object only.

Attribute
Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 2 of 17
CLASS : XII Part - B Information Technology (802)

It is the properties that represent the state of object. Object stores data in the attributes field.

Method
The function which is defined inside the class is known as method. It is a sequence of statements
written together to perform a specific task. It describes the behavior of an object.

OOPs
It stands for Object Oriented Programmings. It is an approach of programming which allows us to
write a program using class. It provides features to secure data.

Features of OOPs
(i) Data Abstraction : The process of declaring variables within class is known as data
abstraction.
(ii) Encapsulation : When we declare variables and methods both inside a class then, this
process is known as encapsulation.
(iii) Inheritance : The process in which one class inherits the attributes and methods of
another class is known as inheritance.
(iv) Polymorphism : The process of creating multiple functions with same name inside a
class is known as polymorphism.

Access Specifier
It defines accessing type of class members. There are four types of access specifiers in Java.
They are :
(i) private : This keyword restricts accessing within class in which it is defined.
(ii) protected : This keyword allows accessing within class in which it is defined as well as
in its sub class
(iii) public : This keyword allows accessing from all classes in the application.
(iv) default : If we do not specify any access specifier then default works. In this case,
members are accessed within same class and package.

Variable
The name of location which stores values of specific data types is known as variable. A variable is
declared with data type. Java has its own set of rules for naming a variable. They are :
(i) It is case sensitive.
(ii) Keywords should not be used as variable name.
(iii) It should be short and meaningful.
(iv) It must start with an alphabet or underscore ( _ ).
(v) It can be alphanumeric.
(vi) It can not have any special symbol except underscore ( _ ).

Data type
The concept of specifying types of data for storing in a variable is known as data type. There are
types of data types in Java. They are :
Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 3 of 17
CLASS : XII Part - B Information Technology (802)

(i) Primitive data type : Predefined data types in Java is known as primitive data type.
Example : short, byte, int, char, long, float, double and boolean.
(ii) Non – primitive data type : User defined data types in Java is known as non-primitive
data type. Example : class, array, String, Interface.
Data Types

Primitive Non-Primitive

class
Integer Float char boolean

array
byte float
Inheritance
short double
String
int

long

Constant
It is a variable whose value can not be changed once it has been assigned. In Java, we can
create constant variable by using final keyword.
Example :
final int n = 5;

Operators
A symbol which performs operations on operands is known as operators.

Types of operators
(i) Assignment operator : = is used to assign a value to the variable.
Ex : int n = 5;
(ii) Arithmetic operator : Those symbols which are used to perform arithmetic calculations
such as addition, subtraction, multiplication and division are known as arithmetic
operator.
Symbol Meaning Example (a = 5, b = 6)
+ Addition a + b = 11
- Subtraction a – b = -1
* Multiplication a * b = 30
/ Division (Quotient) a/b=0
% Modulus (Remainder) a % b = 5
++ Increment a++ = 6
-- Decrement a-- = 4

Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 4 of 17
CLASS : XII Part - B Information Technology (802)

(iii) Relational operator : Those symbols which are used to compare between two values
are known as relational operator. Example :
Symbol Meaning Example
> Greater than 7 > 4 returns true
>= Greater than or equal to 7 >= 4 returns true
< Less than 7 < 4 returns false
<= Less than or equal to 7 <= 4 returns false
== Equal to 7 == 4 returns false
!= Not equal to 7 != 4 returns true
(iv) Logical operator : Those symbols which are used to write two or more conditions
together are known as logical operators. Example :
Symbol Meaning Example (a = 10, b = 5)
&& And a > 8 && b < 7 returns true
|| Or a > 8 || b < 7 returns true
! Not ! (a > 8) returns false
(v) Bit wise operator : Those symbols which are used to perform manipulations on the bit
converted value of a number are known as bit wise operators.

JVM
It stands for Java Virtual Machine. When we write source code (program) in Java then it is saved
with .java extension. After compilation of the program, a new code is generated which is known as
byte code. This code is saved in a new file with extension .class. JVM is a part of JRE (Java
Runtime Environment) which helps to run byte code on any platform.

Starting of Java program


public static void main(String arg[ ])
{

}
Execution of all Java programs starts with main( ) function.
Here “public” keyword is used before main( ) function so that it can be called by JVM.
“static” keyword facilitates us to access class members without creating the object.
“void” In Java, every method has a return type. Here void keyword shows that main( )
method will not return any value.
“main( )” is a predefined method in Java. Java starts execution with this method.
In Java, main( ) method accepts group of strings from user which is called string array.
Here “String arg[ ]” holds the command line arguments in the form of string values.
Note : We can write command line or CUI program in Netbeans IDE by using the following steps :
a) Step 1 : Start Netbeans IDE.
b) Step 2 : Go to “File” menu and click on “New Project”.
c) Step 3 : In the “Categories” pane, select “Java with Ant” and in “Projects” pane, select
“Java Applications”.
d) Step 4 : Enter name of project in “Project Name” box. Select “Create Main Class” check
box and then click “Finish” button.
e) Step 5 : Go to “Projects” window which is on the left side of IDE.
f) Step 6 : Right click on “Source Packages” folder.
g) Step 7 : Click on “New” command then click on “Java Class”.
Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 5 of 17
CLASS : XII Part - B Information Technology (802)

h) Step 8 : Type class name in “Class Name” box and then click “Finish” button.
i) Step 9 : Type the program and save it.
j) Step 10 : Run the program by using Run  Run File or by pressing Shift + F6.

Java Libraries
Java library is a collection of predefined classes and methods. In Java, we can add library by
using import keyword. “import” statement must be written in the first line of the program.
Example :
import java.util.*;
import java.lang.*;

Program 1 : Write a Java program to display Hello Java.


Solution :
public class MyClass { Output
public static void main(String arg[ ])
{
System.out.println("Hello Java");

}
}

Scanner class
It is a predefined class in Java which is used to accept input of primitive types from the user. This
class is available in java.util package. These are the following methods of this class for accepting
different types of values from the user :

Methods Description

nextBoolean( ) Used for accepting Boolean value

nextByte( ) Used for accepting Byte value

nextDouble( ) Used for accepting Double value

nextFloat( ) Used for accepting Float value

nextInt( ) Used for accepting Int value

next( ) Used for accepting string value without space

nextLine( ) Used for accepting string value with space

nextLong( ) Used for accepting Long value

nextShort( ) Used for accepting Short value

Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 6 of 17
CLASS : XII Part - B Information Technology (802)

Program 2 : Write a Java program to enter your name and print.


Solution :
import java.util.Scanner; Output
public class MyClass {
public static void main(String arg[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter your Name : ");
String s = sc.next();
System.out.println("Your Name is : " + s);
}
}
Program 3 : Write a Java program to input any two integer values. Add both values and print the
result.
Solution :
import java.util.Scanner; Output
public class MyClass {
public static void main(String arg[ ])
{
Scanner sc = new Scanner(System.in);
int n1, n2, r;
System.out.println("Enter First Number : ");
n1 = sc.nextInt();
System.out.println("Enter Second Number : ");
n2 = sc.nextInt();
r = n1 + n2;
System.out.println("Sum = "+ r);
}
}

Wrapper class
Wrapper class is a class in Java which is used to convert primitive data type to object type and
vice-versa. These are the following primitive data types and their corresponding wrapper classes :
Primitive Data Type Wrapper Class

char Character

byte Byte

short Short

int Integer

long Long

float Float

Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 7 of 17
CLASS : XII Part - B Information Technology (802)

Program 4 : Write a Java program to input a two digits number. Print reverse of given number.
Solution :
import java.util.Scanner; Output
public class MyClass {
public static void main(String arg[ ])
{
int n, d1, d2, r;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Two Digits Number : ");
n = sc.nextInt();
d1 = n / 10;
d2 = n % 10;
r = d2*10 + d1;
System.out.println("Reverse of " + n + " is " + r);
}
}

Control Structures or Statements


It is used to change flow of execution of the statements in the program. There are three types of
control structures in Java. They are :
(i) Conditional Statements : It alters the flow of execution on the basis of given
conditions. There are three types of conditional statements : if-else, ternary operator
and switch statement.
(ii) Loop : It is used to repeat specific block of codes. There are three types of loop : for,
while and do-while.
(iii) Branching Statements : It is used to change flow of execution in loops. There are two
types of branching statements : break and continue.

if-else statement
if-else statement allows us to alter the execution of statements on the basis of given condition. It
evaluates the given condition at first. If it is true then if-block is executed otherwise else-block is
executed.
Syntax :
if(condition)
{
Statement1;
Statement2;
}
else
{
Statement1;
Statement2;
}
Program 5 : Write a Java program to input a number. Check whether it is even or odd.
Solution :
import java.util.Scanner;
public class MyClass {
Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 8 of 17
CLASS : XII Part - B Information Technology (802)

public static void main(String arg[ ]) Output


{
int n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number : ");
n = sc.nextInt();
if(n%2 == 0)
System.out.println(n + " is even no.");
else
System.out.println(n + " is odd no.");

}
}

Nested if-else statement


The process of writing one if-statement within another if-statement then it is called nested if-
statement. In this case, condition of outermost if-statement is evaluated at first. If it is true then
condition of second if-statement is evaluated. This process continues till the innermost if-
statement.
Syntax :
if(condition)
{
if(condition)
{
Statement;
}
else
{
Statement;
}
}
else
{
Statement;
}

Program 6 : Write a Java program to input any three integer values. Find the largest value and
print the result.
Solution :
import java.util.Scanner; Output
public class MyClass {
public static void main(String arg[ ])
{
int n1, n2, n3;
Scanner sc = new Scanner(System.in);
System.out.print("Enter First Number : ");
n1 = sc.nextInt();
System.out.print("Enter Second Number : ");
Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 9 of 17
CLASS : XII Part - B Information Technology (802)

n2 = sc.nextInt();
System.out.print("Enter Third Number : ");
n3 = sc.nextInt();
if(n1 > n2)
{
if(n1 > n3)
System.out.println("Largest Number : " + n1);
else
System.out.println("Largest Number : " + n3);
}
else
{
if(n2>n3)
System.out.println("Largest Number : " + n2);
else
System.out.println("Largest Number : " + n3);
}
}
}

switch statement
It allows us to test the value of an expression with a series of character or integer values. It
evaluates the given condition or expression at first. If it matches with a case then associated block
of code is executed and continue till the closing brace otherwise default code is executed.
Syntax :
switch(condition/expression)
{
case value1 :
Statement;
case value2 :
Statement;
case value3 :
Statement;
----
default :
Statement;
}
Note :
break : We use break keyword for executing a specific case. “break” keyword terminates the
execution and sends the control to outside the block.

Program 7 : Write a Java program to input values between 1 & 7 and display the name of
respective weekday.
Solution :
import java.util.Scanner;
public class MyClass {
public static void main(String arg[ ]) {
int ch;
Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 10 of 17
CLASS : XII Part - B Information Technology (802)

Scanner sc = new Scanner(System.in); Output 1


System.out.print("Enter Number ( 1 - 7) : ");
ch = sc.nextInt();
switch (ch) {
case 1:
System.out.println("Sunday");
break;
case 2: Output 2
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default :
System.out.println("Wrong Input !");
}
}
}

for loop
It is used to execute the same statements again and again. It is used for known number of
repetitions. It is known as entry controlled loop also. It has three statements in parenthesis. They
are :
(i) Initialization : It is executed first. It executes only once in the beginning of for loop.
(ii) Condition : After initialization, condition is evaluated. If it is true then block of for loop is
executed otherwise control goes to outside the loop.
(iii) Increment / decrement : It runs after executing the block of for loop. After increment /
decrement, control goes to check condition again.
Syntax :
for(initialization ; condition ; increment / decrement)
{
Statements (block of for loop);
}

Program 8 : Write a Java program to input a number. Print table of given number.
Solution :
Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 11 of 17
CLASS : XII Part - B Information Technology (802)

import java.util.Scanner; Output


public class MyClass {
public static void main(String arg[ ]) {
int n, i;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number : ");
n = sc.nextInt();
for(i =1; i<=10; i=i+1)
System.out.println(n + " X " + i + " = " + n * i);
}
}

while loop
It is an entry controlled loop. It is also used for repeating the block of statements. It is mainly used
for unknown number of repetition. It checks the given condition at first. If it is true then block of
statements is executed otherwise control goes to outside the loop.
Syntax :
while(condition)
{
Statements (block of loop)
}

Program 9 : Write a Java program to enter a number of any digits. Count number of digits and
print.
Solution :
import java.util.Scanner; Output
public class MyClass {
public static void main(String arg[ ]) {
int n, c = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a Number of any Digits : ");
n = sc.nextInt();
while(n!=0)
{
c = c + 1;
n = n / 10;
}
System.out.println("Total Number of Digits = " + c);
}
}

do-while loop
It is an exit control loop. It is also used for repetition of statements. It executes the body of loop at
first and then checks the condition. So it runs at least once because the condition is checked after
execution of body of loop.
Syntax :
do
{
Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 12 of 17
CLASS : XII Part - B Information Technology (802)

Statements (body of loop) ;


}while(condition);

Program 10 : Write a Java program to enter base and exponent. Calculate power value and print
the result.
Solution :
import java.util.Scanner; Output
public class MyClass {
public static void main(String arg[ ]) {
int b, e, i, p = 1;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Base : ");
b = sc.nextInt();
System.out.print("Enter Exponent : ");
e = sc.nextInt();
i = 1;
do
{
p = p * b;
i = i + 1;
}while(i<=e);
System.out.println(b + " to the power " + e + " = " + p);
}
}

Arrays
Array is a variable which holds more than one values of same type. It is used to store multiple
values of same data type in a single variable. Array stores all values in a contiguous memory
location. Its index starts with 0. Java has predefined class “Arrays” in the package “java.util” for
array handling.
Syntax :
int[ ] a = new int[5];
Note : Here 5 variables have been created and name of all variables are a[0], a[1], a[2], a[3], a[4].

Program 11 : Write a Java program to store any 10 values in an array. Add all values and print
the result.
Solution : Output
import java.util.Scanner;
public class MyClass {
public static void main(String arg[ ]) {
int[ ] a = new int[10];
int i, s = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter any ten values : ");
for(i = 0; i<10; i++)
{
a[i] = sc.nextInt();
s = s + a[i];
Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 13 of 17
CLASS : XII Part - B Information Technology (802)

}
System.out.println("Sum = " + s);
}
}

Program 12 : Write a Java program to create a class for displaying “Hello Java”.
Solution :
public class MyClass { Output
public static void main(String arg[ ]) {
demo d = new demo();
d.display();
}
}
class demo
{
public void display( )
{
System.out.println("Hello Java");
}
}

Program 13 : Write a Java program to create a class for adding two values.
Solution :
public class MyClass { Output
public static void main(String arg[ ]) {
demo d = new demo();
int r;
r = d.display();
System.out.println("Result = " + r);
}
}
class demo
{
int n1, n2;
public int display( )
{
n1 = 10;
n2 = 20;
return(n1+n2);
}
}

Constructor
A special member method which has the same name as class is known as constructor. It is used
to initialize the member variables of the class. It has no return type. It is called automatically when
we create object of a class.

Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 14 of 17
CLASS : XII Part - B Information Technology (802)

Program 14 : Write a Java program to create a constructor for initialize name, roll and class of a
student and print it.
Solution :
public class MyClass { Output
public static void main(String arg[ ]) {
demo d = new demo();
d.display();
}
}
class demo
{
String name;
int roll, clas;
demo()
{
name = "Rajesh Kumar";
roll = 1;
clas = 12;
}
void display( )
{
System.out.println("Name : " + name);
System.out.println("Roll : " + roll);
System.out.println("Class : " + clas);
}
}
String manipulation methods
String is a sequence of characters. Java has String class and several inbuilt methods to perform
string manipulations. These are the following string methods in Java :
Method Description Return type value
charAt( ) It returns character of specific index char
concat( ) It adds at last of given string and returns a string String
contains( ) It checks existence of given character boolean
endsWith( ) It checks whether a string ends with the specified boolean
character
equals( ) It compares between two strings and returns true if boolean
strings are equal otherwise it returns false.
equalsIgnoreCase( ) It compares between two strings by ignoring lower boolean
or upper case
indexOf( ) It returns position of the first occurrence of int
specified characters in a string.
isEmpty( ) It checks whether a string is empty or not. boolean
length( ) It returns total number of characters in the given int
string
replace( ) It replaces a string with another string String
replaceAll( ) It replaces given string in the given string with String
specified string.
Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 15 of 17
CLASS : XII Part - B Information Technology (802)

Method Description Return type value


startsWith( ) It checks whether a string starts with specified boolean
characters or not.
substring( ) It returns a new string from given starting position String
to given end position.
toLowerCase( ) It converts given string into lower case String
toString( ) It converts from other type to string type. String
toUpperCase( ) It converts given string into upper case. String
trim( ) It removes extra space from both sides in the given String
string
valueOf( ) It returns string value. String

Program 15 : Write a Java program to use string methods.


Solution :
import java.util.Arrays;
public class MyClass { Output
public static void main(String arg[ ]) {
String s = "Programming Language ";
System.out.println(s.charAt(5));
System.out.println(s.concat("Java"));
System.out.println(s.contains("Language"));
System.out.println(s.endsWith("age "));
System.out.println(s.equals("Programming Language "));
System.out.println(s.equalsIgnoreCase("programming language "));
System.out.println(s.indexOf("L"));
System.out.println(s.isEmpty());
System.out.println(s.length());
System.out.println(s.replace("Programming", "Java"));
System.out.println(s.replaceAll("Programming", "J"));
System.out.println(s.startsWith("Pro"));
System.out.println(s.substring(3, 7));
System.out.println(s.toLowerCase());
System.out.println(s.toUpperCase());
System.out.println(s.trim());
}
}

Threads
Java provides features of multithreading. Multithreading means execution of multiple processes at
same time. In Java we can create thread in two ways :
(i) Extending the “Thread” class : In this case, Java uses “run( )” method of “Thread” class
to execute the task. It is called by using “start( )” method of “Thread” class.
(ii) Implementing the “runnable” interface : In this case, Java uses “run( )” method of
“Runnable” interface to execute the task. It is called by using “start( )” method of
“Runnable” interface.

Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 16 of 17
CLASS : XII Part - B Information Technology (802)

Program 16 : Write a Java program to create thread by extending Thread class.


Solution :
public class MyClass{ Output
public static void main(String arg[ ]) {
myThread mt1 = new myThread();
mt1.start();
myThread mt2 = new myThread();
mt2.start();
}
}
class myThread extends Thread
{
public void run()
{
System.out.println("It is my Thread");
}
}

Program 17 : Write a Java program to create thread by implementing Runnable interface.


Solution :
public class MyClass { Output
public static void main(String arg[ ]) {
myThread mt1 = new myThread();
Thread t1 = new Thread(mt1);
t1.start();
Thread t2 = new Thread(mt1);
t2.start();
}
}
class myThread implements Runnable
{
public void run()
{
System.out.println("It is my Thread");
}
}

Kumar Gourab (DAV PS, CRRC, Medical Road, Gaya Email : [email protected]) Page 17 of 17

You might also like