), MANIPAL INSTITUTE OF TECHNOLOGY
uf” MANIPAL
(A constituent unit of MAHE, Manipal)
@
Manipal Academy of Higher Education, Manipal — 576 104
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CERTIFICATE
This is to certify that Ms./Mr.
Reg. No.: Section: Roll No.:
has satisfactorily completed the LAB EXERCISES PRESCRIBED FOR OBJECT
ORIENTED PROGRAMMING LAB (CSE 2163) of Second Year B.Tech.
Degree in Computer Science and Engineering at MIT, Manipal, in the Academic
Year 2019 — 2020.
Date:
Signature
Faculty In ChargeCONTENTS
nab Title Page No. | Remarks
Course Objectives and Outcomes iii
Evaluation Plan iii
Instructions to the Students iii
Sample Lab Observation Note Preparation vi
Introduction to Java vi
1. | Simple Java Programs using Control Structures, 13
2 1D and 2D Arrays 47
3. | Classes and Objects 8-12
4. | Constructors and Static Members 13-16
5. | Strings 17-20
6. | Inheritance and Packages 21-27
7. | Interfaces and Exception Handling 28-33
8. | Multithreading 34-40
9. | Generies 41-43
10. | Input/Output 4447
11. | JavaFX and Event Handling -Part I 48-52
12. | JavaFX and Event Handling -Part IL 53-57
References 58
Java Quick Reference Sheet 59Course Objectives
© To understand the concepts of object orientation using Java
© To write and execute application programs
To develop skills in concurrent programming
© To develop efficient Graphical User Interfaces (GUD) using JavaFx components
© To understand event handling mechanism of Java
Course Outcomes
At the end of this course, students will be able to
© Understand object-oriented paradigm of software development
© Use the constructs of an object-oriented language Java in achieving object oriented
principles
© Understand the packages of Java to develop concurrent programs
* Achieve high level reusability using generics
Design and implement small Java applications using JavaFx
Evaluation plan
«Internal Assessment Marks : 60%
Y Continuous evaluation component (for each experiment):10 marks
The assessment will depend on punctuality, program execution, maintaining the
observation note and answering the questions in viva voce
Y Total marks of the 12 experiments reduced to marks out of 60
« End semester assessment of 2 hour duration: 40 %
INSTRUCTIONS TO THE STUDENTS.
Pre-Lab Session Instructions
1. Students should carry the Lab Manual Book and the required stationery to every lab
session
2. Be in time and follow the institution dress code
3. Must Sign in the log register provided
4. Make sure to occupy the allotted seat and answer the attendance
iii5.
Adhere to the rules and maintain the decorum
In-Lab Session Instructions
Follow the instructions on the allotted exercises
Show the program and results to the instructors on completion of experiments
On receiving approval from the instructor, copy the program and results in the Lab
record
Prescribed textbooks and class notes can be kept ready for reference if required
General Instructions for the exercises in Lab
.
Implement the given exercise individually and not in a group.
The programs should meet the following criteria:
© Programs should be interactive with appropriate prompt messages, error
messages if any, and descriptive messages for outputs.
Programs should perform input validation (Data type, range error, ete.) and give
°
appropriate error messages and suggest corrective actions.
© Comments should be used to give the statement of the problem and every
member function should indicate the purpose of the member function, inputs and
outputs.
© Statements within the program should be properly indented.
© Use meaningful names for variables, classes, interfaces, packages and methods.
© Make use of constant and static members wherever needed.
Plagiarism (copying from others) is strictly prohibited and would invite severe
penalty in evaluation.
The exercises for each week are divided under three sets:
© Solved exercise
© Lab exercises —to be completed during lab hours
© Additional Exercises — to be completed outside the lab or in the lab to enhance
the skill
In case a student misses a lab class, he/she must ensure that the experiment is
completed during the repetition class with the permission of the faculty concerned
but credit will be given only to one day’s experiment(s).
iv© Questions for lab tests and examination are not necessarily limited to the questions
in the manual, but may involve some variations and / or combinations of the
questions.
© A sample note preparation is given as a model for observati
The students should not
Bring mobile phones or any other electronic gadgets to the lab.
© Go out of the lab without permission.SAMPLE LAB OBSERVATION NOTE PREPARATION
Lab No.: 1 Date:
Title: Simple Java Programs using Control Structures
1._A Java program Sample.java to display Hello Java message
class Sample{
public static void main(String args[ ]){
System. out. printin(“Hello Java”);
Sample input and output:
Hello Java
Introduction to Java
Java is both compiled and interpreted. Programs written in Java are compiled into
machine language, but it is a machine language for a computer that doesn’t really exist.
This so-called “virtual” computer is known as the Java virtual machine (JVM). The
machine language for the JVM is called Java byte-code. But a different Java bytecode
interpreter is needed for each type of computer. Once a computer has a Java bytecode
interpreter, it can run any Java bytecode program. In other words, the same Java
bytecode program can be run on any computer that has such an interpreter. This is one
of the essential features of Java: the same compiled program ean be run on many
different types of computers as illustrated below. The combination of Java and Java
bytecode together makes Java the platform-independent, secure, and network-
compatible while allowing programming in a modem high-level object-oriented
language.
viJava Interpreter
a for Mac OS
Java
Java Interpreter
Compiler |——™ Bytecode ———m] “40P wines
Java
Program
Program
_ “Java interpreter
for Linux
Fig 1.1 Byte Code Generation and running in different OS
Java is:
Object Oriented; Platform independent
Simple: Secure
Architectural-neutral; Portable
Robust; Multi-threaded
Interpreted; High Performance
Distributed; DynamicLab No.: 1 Date:
Simple Java Programs using Control Structures
Objectives:
In this lab, student will be able to:
1 Write Java programs
2 Compile and interpret Java programs
3. Debug Java programs
Solved exercise
1. A Java program SampleJavato display Hello Java
dass Sample{
public static void main(String argsf ]){
System.out printin(“Hello Java”);
PETES OXe
ed new
\new> javac Simple. java
ew> java Simple
Hello Java
Class Declaration
© class Sample: It declares an object oriented construct called a class. Java is a pure
object oriented language requires variable declarations and method definitions be
placed inside the class. The class keyword defines a new class. Sample is an
identifier or name of the class. Every class definition in Java begins with an opening
brace({) and ends with a matching closing brace(}).
public static void main (String args[]) : This defines a method named main. Every
Java application program must include the main() method. This is the starting point
for the interpreter to begin the execution of the program. There may be any number
of classes in a Java program. The name of the class containing main( ) method must
1be the file name with extension java. String is the built-in class available in java.
lang package, which gets imported automatically to all the java programs.
© public, static and void: These are the three keywords of Java having the following
meanings:
public: It is an access specifier that declares the main method as unprotected and
therefore makes it accessible to all other classes
static: It declares this method as one that belongs to the entire class and not a part
of any objects of the class. The main must always be declared as static
since the interpreter uses this method before any objects are created.
void: It indicates that the main( ) method does not retumn anything,
© System.out println ("Hello Java");This is similar to the cout=<"Hello Java"<
javac Student. java
D:\program files\Java\jdki.7.6_88\bin>java Student
inside default constructor
default value of x -@
PSCC cSt saad
the values are 111 Karan
Static variables and methods
Normally a class member must be accessed through an object of its class, but it is
possible to create a member that can be used without reference to a specificinstance. To
create this type of member, precede its declaration with the keyword static. When a
member is declared static, it can be accessed before any objects of its class are created
without reference to any object. Both methods and wariables can be declared as static
Following example illustrates the usage of static variable and static method:
class StaticMeth(
static int wal=1024,
static int valDiv20{
return wal/2;,
}
class SDemo2{
14public static void main(String[] args)
System.out. printIn(“val is “+StaticMeth. val):
System.out.println(“StaticMeth. valDiv2() : *+StaticMeth.valDiv20);
StaticMeth.val=
System.out.printin(“val is “+StaticMeth.val):
System.out.printIn(“StaticMeth. valDiv2() : *+StaticMeth.valDiv20);
}
3
Output
val is 1024
StaticMeth.valDiv20 : 512
valis 4
StaticMeth.valDiv20 : 2
Since the methodvalDiv2() is declared static, it can be called without any instance of its
class StaticMeth being created, but by using class name.
Lab Exercises:
1. Consider the already defined Complex class. Provide a default constructor and
parameterized constructor to this class. Also provide a display method. Illustrate all
the constructors as well as the display method by defining Complex objects.
2. Consider the already defined Time class, Provide a default constructor, and
parameterized constructor. Also provide a display method. Illustrate all the
constructors as well as the display method by defining Time objects.
3. Define a class to represent a Bank account. Include the following members.
Data members:
1. Name of the depositor
2. Account number.
3. Type of account.
4. Balance amount in the account.
5. Rate of interest (static data)
Provide a default constructor and parameterized constructor to this class. Also
provide Methods:
1. To deposit amount.2. To withdraw amount after checking for minimum balance.
3. To display all the details of an account holder.
4, Display rate of interest (a static method)
Ilustrate all the constructors as well as all the methods by defining objects.
. Create a class called Counter that contains a static data member to count the number
of Counter objects being created. Also define a static member function called
showCount() which displays the number of objects created at any given point of
time. Illustrate this.
Additional Exercises
1.
Define a class IntArr which hosts an array of integers. Provide the following
methods:
1. A default constructor.
2. A parameterized constructor which initializes the array of the object.
3. A method called display to display the array contents.
4. A method called search to search for an element in the array.
5. A method called compare which compares 2 IntArr objects for equality,
Define a class called Customer that holds private fields for a customer ID number,
name and credit limit, Include appropriate constructors to initialize the instance
variables of the Customer Class. Write a main() method that declares an array of
5 Customer objects. Prompt the user for values for each Customer, and display all
5 Customer objects.Lab No.: 5 Date:
Strings
Objectives:
In this lab, student will be able to:
1. Know different ways of creating String objects and constants
2. Leam and use string handling methods
3. Know the difference between String and StringBuffer classes
Introduction to Strings:
© String is probably the most commonly used class in Java’s class library. Every
string created is actually an object of type String. Even string constants are actually
String objects. For example, in the statement System.out println (“This is a String.
too”); the string “This is a String, too” is a String constant.
© The objects of type String are immutable: once a String object is created, its
contents cannot be altered. To change a string, create a new one that contains the
modifications or Java defines a peer class of String, called StringBuffer, which
allows strings to be altered, so all of the normal string manipulations are still
available in Java.
© Strings can be constructed in a variety of ways. The easiest is to use a statement like
this:
String myString = “this is a test”;
System.out.printin(myString):
* In Java, + operator is used to concatenate two strings.
For example, this statement String myString = “I” + “like” + “Java.”;
results in myString containing “I like Java.”
© Some of the important methods of String class.
boolean equals(String object) // To test two strings for equality
int length() J obtain the length of a string
charcharAt(int index) J/ To get the character at a specified index
within a string
17© Like array of any other type of objects, array of Strings is also possible.
Solved exercises
1. Program to demonstrate Strings.
class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String stOb2 = "Second String”;
String strOb3 = strOb1 +" and" + strOb2:// using ‘+ for concatenation
System.out.printIn(strOb 1);
System.out.printIn(strOb2);
System.out. printIn(strOb3);
3
3
‘The output produced by this program is shown here:
First String
Second String
First String and Second String
2. Program to demonstrate array of Strings.
class StringArray {
public static void main(String args[]) {
String str[] = { "one", "two", "three" };
for(inti=0; ijavac inheritancePxd -java
D:\progran files\Java\jdki.?.8_8@\bin>java inheritanceEx1
SUE Ce et a ee)
fiviangle isoutlined
Width and height are 4.0 and 4.0
fiviangle isfilled
Introduction to Packages:
While naming a class, the name chosen for a class is reasonably unique and not collides
with class names chosen by other programmers, Packages are containers for classes that
are used to keep the class name space compartmentalized The package is both anaming
and a visibility control mechanism. Ik is possible to define classes inside a package that
are not accessible bytecede outside that package
Simple example of java package
The package keyword is used to create a package in java.
iIsave as Simple.java
package mypack;
22public class Simple{
public static void main(String args[])f
System.out.println("Weleome to package"):
3
3
To compile java package
Give the command with the following format in the terminal:
javac -d directory javafilename
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file, Any
directory name like /home (in case of Linux), d:/abe (in case of windows) ete, can be
used. To keep the package within the same directory, use . (dot).
To run java package program: Use fully qualified name e.g. Java mypack.Simple to
run the class.
Output:
Welcome to package
To access a 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 package.*is used, 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.*
fIsave by Ajjava
package pack:
public class Af
public void msg(){System.out.printIn("Hello"):3
23}
iIsave by B,java
package mypack:
import pack.*;
class BE
public static void main(String args[])
A obj =new AQ;
obj.msg();
3
3
Output:
Hello
2) Using packagename.classname
If package.classname is imported, then only declared class of this package will be
accessible.
Example of package by import package.classname
Jsave by A.java
package pack;
public class Af
public void msg(){System.out printIn("Hello");}
3
disave by B,java
package mypack;
import pack. A;
class Bf
public static void main(String args[]){
A obj = new AQ);
obj.msgQ):
3
3
Output:
Hello
3) Using fully qualified name
24If the fully qualified name is used then only declared class of this package will be
accessible. Now there is no need to import, But the fully qualified name must be used
every time while 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
save by A,java
package pack:
public class Af
public void msg(){System.out printIn("Hello"):}
JIsave by B,java
package mypack;
class Bf
public static void main(String args[]){
pack. Aobj = new pack. AQ;//using fully qualified name
obj.msg();
Output:
Hello
Lab Exercises
1. Create a Person class with private instance variables for the person’s name and birth
date. Add appropriate accessor methods for these variables. Then create a subclass
College Graduate with private instance variables for the student’s GPA and year of
graduation and appropriate accessors for these variables. Include appropriate
constructors for your classes. Then ereate a class with mainQ) method that
demonstrates your classes,
2. Define a class Maximum with the following overloaded methods
25max (which finds maximum among three integers and returns the maximum
integer)
ii) max (which finds maximum among three floating point numbers and returns
the maximum among them)
iii) max (which finds the maximum in an array and returns it)
iv) max (which finds the maximum in a matrix and returns the result)
Place this in a package called pl. Let this package be present in a folder called
“myPackages”, which is a folder in your present working directory
(eg: c\student\3rdsem \mypackages'p1). Write a main method to use the methods of
Max class in a package p1.
. Create an abstract class Figure with abstract method area and two integer
dimensions. Create three more classes Rectangle, Triangle and Square which extend
Figure and implement the area method. Show how the area can be computed
dynamically during run time for Rectangle, Square and Triangle to achieve dynamic
polymorphism. (Use the reference of Figure class to call the three different area
methods)
|. Create a Building class and two subclasses, House and School. The Building class
contains fields for square footage and stories. The House class contains additional
fields for number of bedrooms and baths. The School class contains additional fields
for number of classrooms and grade level (for example, elementary or junior high).
All the classes contain appropriate get and set methods. Place the Building, House,
and School classes in a package named com.course.structure, Create a main method
that declares objects of each type and uses the package.
Additional Exercises
1.
Design a base class called Student with the following 2 fields:- (i) Name (ii) Id.
Derive 2 classes called Sports and Exam from the Student base class, Class Sports
has a field called s_grade and class Exam has a field called e grade which are
integer fields. Derive a class called Results which inherit from Sports and Exam.
This class has a character array or string field to represent the final result, Also it
26has a method called display which ean be used to display the final result. Illustrate
the usage of these classes in main.
Develop following methods
i) IntSort (sort n integers in ascending order using Selection Sort)
ii) BinSearch (performs Binary search for an element among a given list of
integers)
Place this in a package called pIntegers. Let this package be present in a folder
called “myPackages”, which is a folder in your present working directory (eg:
c\student\3rdsem\mypackages\pIntegers). Write a main method in package pMain
to read an array of integers and display it. Using the methods IntSort and BinSearch
from package pIntegers perform sort and search operations on the list of array
elements.
27Lab No.: 7 Date:
Interfaces and Exception Handling
Objectives:
In this lab student will be able to :
1. Understand interface fundamentals
Implement interfaces and apply interface references
. Use interface constants, extend interfaces.
Know the exception mechanism of Java
yawn
Know Java’s built-in exceptions and to create custom exceptions
Introduction to Interfaces:
An interface is a blueprint of a class. It has static constants and abstract methods only.
There are mainly three reasons to use interface. They are given below.
i) It is used to achieve absolute abstraction.
ii) Interface can be used to achieve the functionality of multiple inheritances.
iii) It can be used to achieve loose coupling,
Solved exercise
1. Program to illustrate usage of interfaces
interface Printablef
void print();
3
interface Showable{
void show;
3
class A implements Printable,Showable{
public void print(){System.out.printIn("Hello");}
public void show(){System.out.printIn("Welcome"):}
28publie static void main(String args[]){
A obj = new AQ);
obj.print();
obj.show();
3
3
Output:
Hello
Welcome
Introduction to Exceptions
A method catches an exception using a combination of the try and eatch keywords. A
try/catch block is placed around the code that might generate an exception.
2. The following code has an array declared with 2 elements. Then the code tries to
access the 3rd element of the array which throws an exception.
public class ExcepTest{
public static void main(String args[]){
int a[ ] = new int[2]:
tryt
System. out. println(""Access element three :" + a[3]);
$
cateh(ArraylndexOutOfBoundsException e){
System. out printin("Exception thrown :" +e);
}
finally{
a[0] = 6;
System.out.printin("First element value: " +a[0]);
System.out. println("The finally statement is executed");
334
Output:
Exception thrown ;java.lang, ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
29The finally Keyword: The finally keyword is used to create a block of code that
follows a try/eatch block. A finally block of code always executes, whether or not an
exception has occurred. Using a finally block allows to run any cleanup-type statements
like closing of file.
The throwsithrow Keywords: If a method does not handle a checked exception, the
method must declare it using the throws keyword. The throws keyword appears at the
end of a method's signature. The throw keyword can be used to throw an exception,
either a newly instantiated one or an exception that is just caught
User defined Exceptions
Note the following while creating own exceptions:
« Allexceptions must be a child of Throwable.
+ To create checked exception that is automatically enforced by the Handle or Declare
Rule, extend the Exception class.
+ To create a runtime exception, extend the Runtime Exception class.
3. The following Insufficient Funds Exception class is a user-defined exception that
extends the Exception class, making it a checked exception. An exception class is
like any other class, containing useful fields and methods.
import java.io.*;
1/ File Name InsufficientFundsException java
public class InsufficientFundsException extends Exception{
private double amount;
public InsufficientFundsException(double amount){
this.amount = amount;
3
public double getAmount(){
return amount;
To demonstrate using our user-defined exception, the following Checking Account class
contains a withdraw) method that throws an Insufficient Funds Exception.
// File Name Checking Account java
&
import java.
public class Checking Account {
30private double balance;
privateint number;
publicCheckingAccount(int number){
this.number = number;
3
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException {
if(amount <= balance) {
balance -= amount;
3
else{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
3
/The following BankDemo program demonstrates invoking the deposit() and
withdraw() methods of CheckingAccount.*/
‘i File Name BankDemo java
public class BankDemof
public static void main(String [] args) {
Checking Account ¢ = new CheckingAccount(101);
System. out.printin("Depositing $500...");
c.deposit(500.00),
try {
System.out. printin(”\nWithdrawing $100...");
c.withdraw(100.00);
System. out. printin("\nWithdrawing $600...");
c.withdraw(600.00);
3
catch(InsufficientFundsException e) {
31System.out-printin("Sorry, but you are short $" + e.getAmount()):
e.printStackTrace():
3
3
3
Output
Depositing $500...
Withdrawing $100.
Withdrawing $600.
Sorry, but you are short $200.0
InsufficientFundsException
atCheckingAccount.withdraw(Checking Account java:25)
atBankDemo.main(BankDemo,java:13)
Lab Exercises
1. Create a class Phone{string brand, int memCapacity}, which contains an interface
Callable{makeAudioCall(string cellNum), make VideoCall(string cellNum)}. Create
subclasses BasicPhone and SmartPhone and implement the methods appropriately.
Demonstrate the creation of both subclass objects by calling appropriate
constructors which accepts values form the user. Using these objects call the
methods of the interface.
2. Define a class CurrentDate with data members day, month and year. Define a
method createDate() to create date object by reading values from keyboard. Throw a
user defined exception by name InvalidDayException if the day is invalid and
InvalidMonthException if month is found invalid and display current date if the date
is valid. Write a test program to illustrate the functionality.
3. Design a Student class with appropriate data members as in Lab 5. Provide your
own exceptions namely Seats Filled Exception, which is thrown when Student
registration number is >XX25 (where XX is last two digits of the year of joining)
Show the usage of this exception handling using Student objects in the main. (Note:
Registration number must be a unique number)
324, Design an interface called Series with the following methods
i) Get Nest (returns the next number in series)
ii) reset(to restart the series)
iii) set Start (to set the value from which the series should start)
Design a class named By Twos that will implement the methods of the interface
Series such that it generates a series of numbers, each two greater than the previous
one, Also design a class which will inelude the main method for referencing, the
interface.
Additional Exercises
1. Design a stack class. Provide your own stack exceptions namely Push Exception and
Pop Exception, which throw exceptions when the stack is full and when the stack is
empty respectively. Show the usage of these exceptions in handling a stack object in
the main.
2. Design a class Student with the methods, get Number and put Number to read and
display the Roll No. of each student and get Marks() and put Marks() to read and
display their marks. Create an interface called Sports with a method put Grade() that
will display the grade obtained by a student in Sports. Design a class called Result
that will implement the method put Grade() and generate the final result based on
the grade in sports and the marks obtained from the superclass Student.
33Lab No.: 8 Date:
Multithreading
Objectives:
In this lab, student will be able to:
1. Write and execute multithreaded programs
2. Understand how java achieves concurrency through APIs
3. Leam language level support for achieving synchronization
4.
Know and execute programs that use inter-thread communication
Introduction to Multithreading:
Java makes concurrency available through APIs. Java programs can have multiple
threads of execution, where each thread has its own method-call stack and program
counter, allowing it to execute concurrently with other threads while sharing with them
application-wide resources such as memory. This capability is called multithreading.
A multithreaded program contains two or more parts that can run concurrently. Each
part of such a program is called a thread, and each thread defines a separate path of
execution.
Creating a Thread:
Java defines two ways in which this can be accomplished:
+ Implement the Runnable interface
+ Extend the Thread class
Solved exercise
1. Program to demonstrate the creation of thread by implementing Runnable interface:
class NewThread implements Runnable {
Thread t;
NewThread() {
34// Create a new, second thread
t=new Thread(this, "Demo Thread");
System. out.println("Child thread: " +1);
tstart(); // Start the thread, this will call run method
3
public void run() { #/ This is the entry point for the second thread.
try f
for(int i= 5; i> 0; i+) £
System. out. printin("Child Thread: " +i);
Thread sleep(500);
3
catch (InterruptedException e) {
System. out. printin("Child interrupted."),
3
System. out. printin("Exiting child thread.");
3
Class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5: i> 0: i+) £
System.out. printin(”Main Thread: " + i):
Thread.sleep( 1000);
}
3
catch (InterruptedException e) {
System.out. printIn(”Main thread interrupted.");
3
System.out.printin("Main thread exiting.");
}
3
‘The output may vary based on processor speed and task load
35Output:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
2. Program to demonstrate the creation of thread by extending Thread class:
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System. out.printIn("Child thread: " + this);
start(); // Start the thread, this will call run method
}
/! This is the entry point for the second thread.
public void rund {
try {
for(int i = 5; i> 0; i--) {
System.out.printin¢’Child Thread: " +i);
Thread.sleep(500);
}
}
36catch (nterruptedException e) {
System out printin("Child interrupted.");
}
System. out-println("Exiting child thread."),
}
}
Class Extends Thread {
public static void main(String args{)} {
new NewThread(); —/f create a new thread
wey {
for(int i = 5, i> 0:1) (
System. out printin("Main Thread: " +);
Thread.sl eep(1000);
}
}
catch (nterruptedException e) £
System. out printin("Main thread interrupted."),
)
System out printla ("Main thread exiting,");
(Siac G ests Gee
373. Create multiple threads.
class NewThread implements Runnable {
String name; // name of thread
‘Thread t:
NewThread(String threadname) {
name = threadname:
t =new Thread(this, name);
System.out.println(""New thread: " + t),
tstart( ); / Start the thread
3
public void rung) { !/ This is the entry point for thread.
try {
for(int i = is)
System.out.printin(name +"; " +i);
Thread.sleep(1000);
}
}
catch (InterruptedException e) {
System.out.printIn(name + "Interrupted");
3
System.out.printIn(name + " exiting.");
3
}
class Multi'ThreadDemo {
public static void main(String args[ ]) £
new NewThread("One"); start threads
new NewThread("Two");
new NewThread("Three");
try ft
Thread.sleep(10000); J/ wait for other threads to end
}
38catch (Interrupte dException e) {
System. out. println("Main thread Interrupted");
}
System out printin("Main thread exiting."),
Main thread exiting.
Lab exercises
1. Create a class by extending Thread Class to print a multiplication table of a number
supplied as parameter. Create another class Tables which will instantiate two objects
of the abowe class to print multiplication table of 5 and 7,
2. Write and execute a java program to create and initialize a matrix of integers. Create
n threads( by implementing Runnable interface) where n is equal te the umber of
rows in the matrix. Each of these threads should compute a distinct row sum. The
main thread computes the complete sum by looking into the partial sums given by
the threads
3. Write and execute a java program to implement a producer and consumer problem
using Inter-thread communi cati on.
394. Write a program to demonstrate thread priority.
Additional exercise:
1. Write and execute a java program to create five threads, the first thread checking the
uniqueness of matrix elements, the second calculating row sum, the third calculating
the column sum, the fourth calculating principal diagonal sum, the fifth calculating
the secondary diagonal sum of a given matrix. The main thread reads a square
matrix from keyboard and will display whether the given matrix is magic square or
not by obtaining the required data from sub threads.
2. Create a Counter class with a private count instance variable and two methods. The
first method: synchronized void inerement( ) tries to inerement count by 1, If count
is already at its maximum of 3, then it waits until count is less than 3 before
incrementing it. The other method: synchronized void decrement( ) tries to
decrement count by 1. If count is already at its minimum of 0, then it waits until
count is greater than 0) before decrementing it. Every time either method has to wait,
it displays a statement saying why it is waiting. Also, every time an increment or
decrement occurs, the counter displays a statement that says what occurred and
shows count’s new value.
A. Create one thread class whose run( ) method calls the Counter’s increment( )
method 20 times. In between each call, it sleeps for a random amount of time
between 0 and 500 milliseconds.
B. Create one thread class whose run( ) method calls the Counter’s decrement( )
method 20 times. In between each call, it sleeps for a random amount of time
between 0 and 500 milliseconds.
C. Write a Counter User class with a main() method that creates one Counter and
the two threads and starts the threads running.
Note: Instead of creating two thread classes, you are free to create just one thread
class that either increments or decrements the counter, depending on a
parameter passed through the thread class's constructor.
40Lab No.: 9 Date:
Generics
Objectives:
In this lab, student will be able to:
1. Understand the benefits of generics
2. Create generic classes and methods
Introduction to Generics:
Generics are a powerful extension to Java because they streamline the creation of type-
safe, reusable code. The term generics means parameterized types. Parameterized types
are important because they enable the programmer to create classes, interfaces, and
methods in which the type of data upon which they operate is specified as a parameter.
Using generies, it is possible to create a single class, for example, that automatically
works with different types of data. A class, interface, or method that operates on a
parameterized type is called generio, as in generic class or generic method.
Solved exercise:
1. Program defines two classes, the generic class Gen, and the second is GenDemo,
which uses Gen. Here, T is a type parameter that will be replaced by a real type
when an object of type Gen is created.
class Gen {
Tob; // declare an object of type T
// Pass the constructor a reference to an object of type T.
Gen(T 0) {
ob =o;
3
‘| Return ob.
T getob() {
returnob;
3
ié Show type of T.
41void showType() {
System.out. printin("Type of T is" +ob.getClass().getName()):
3
// Demonstrate the generic class.
Class GenDemo {
public static void main(String args[])
// Create a Gen reference for Integers.
GeniOb;
/ Create a Gen object and assign its
// reference to iOb, Notice the use of autoboxing
// to encapsulate the value 88 within an Integer object.
iOb = new Gen(88);
JJ Show the type of data used by iOb.
iOb.showType();
‘| Get the value in iOb. Notice that no cast is needed.
int v =iOb.getob;
System. out. printin("value: " + v);
System. out.printin();
// Create a Gen object for Strings.
GenstrOb = new GeniOb;
‘The type Integer is specified within the angle brackets after Gen, In this case, Integer is
a type argument that is passed to Gen’s type parameter, T. This effectively creates a
version of Gen in which all references to T are translated into references to Integer.
Thus, for this declaration, ob is of type Integer, and the retum type of getob( ) is of type
Integer.
The next line assigns to iOba reference to an instance of an Integer version of the
Genclass
iOb = new Gen(88);
Generies Work Only with Objects. Therefore, the following declaration is illegal:
Ger
-strOb = new Gen(53);_// Error, can't use primitive type
Lab exercises:
1. Write a generic method to exchange the positions of two different elements in an
array.
2. Define a simple generic stack class and show the use of the generic class for two
different class types Student and Employee class objects.
3. Define a generic List class to implement a singly linked list and show the use of the
generic class for two different class types Integer and Double class objects.
4, Write a program to demonstrate the use of wildeard arguments.
Addi
1. Write a generic method that can print array of different type using a single Generic
method:
nal exercises:
2. Write a generic method to return the largest of three Comparable objects.
43Lab No.: 10 Date:
Input /Output
Objectives:
In this lab, student will be able to:
1. Understand the meaning of streams, byte stream and character stream classes
2. Know to work with files
Introduction:
Streams
Java programs perform VO through streams. A stream is an abstraction that either
produces or consumes information. A stream is linked to a physical device by the Java
V/O system. All streams behave in the same manner, even if the actual physical devices
to which they are linked differ. Thus, the same I/O classes and methods ean be applied
to any type of device. This means that an input stream can abstract many different kinds
of input: from a disk file, a keyboard, or a network socket. Likewise, an output stream
may refer to the console, a disk file, or a network comnection. Stream abstracts various
types of VO devices in coding and provides a common access to all those varieties. Java
implements streams within class hierarchies defined in the java.io package.
Byte Streams and Character Streams
Java defines two types of streams: byte and character. Byte streams provide a
convenient means for handling input and output of bytes. Byte streams are used, for
example, when reading or writing binary data, Character streams provide a convenient
means for handling input and output of characters. They use Unicode and, therefore, ean
be intemationalized. Also, in some cases, character streams are more efficient than byte
streams.
44Solved exercises:
1, Program to copy contents of input.txt to output.txt using byte stream classes
import java.io.*;
public class FileCopy {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("D:\input.txt");
out = new FileOutputStream("D:\\output txt");
int c;
while((c = in.read()) !==1) {
out. write(c);
}
}finally {
if (in != null) {
in.close();
$
if (out != null) {
out.close();
2. Program to copy contents of input.txt to output.txt using character stream classes
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null,
try {in = newFileReader("D:\\input L.txt");
out = newFileWriter("D:\\output | txt");
int c.
while ((c = in.read()) != -1) {
out.write(c);
3
finally {
if (in = null) {
in.close();
}
if (out != mull {
out.close();
}
3. Program to display contents of a directory.
import java.io.File;
public class ReadDir {
public static void main(String[] args) {
File file = null;
String] paths;
ty{
fil
new File("D:
create new file object
paths = file.listQ; J/ array of files and directory
for(String path:paths) _// for each name in the path array
t
System.out.println(path); // prints filename and directory name
3
}eateh(Exception e){
e.printStackTrace(), —_// if any error occurs
46Lab exercises:
1. Write a program to display the listing of a given directory and its subdirectories
using recursion.
2. Count the number of characters, numbers (sequence of 1 or more digits), words and
lines from a file “fileNames.txt’ and place the result on the console.
3. Write and execute a Java program that reads a specified file and searches for a
specified word, printing all the lines on which that word is found, by preceding it
with its line number.
4. Write a program to copy the contents of one file to another file using FileReader and
FileWriter classes,
Additional exercises:
1. Assume that there exists a file with different file names stored in it. Every file name
is placed on a separate line. Create two threads, which scan the first half, and the
second half of the file respectively, to search the filenames which end with java
Write those file names onto the screen.
2. Write a program to copy all files from source directory onto destination directory.
Read source and destination directory names from keyboard.
47Lab No.: I Date:
JavaFX and Event Handling -Part I
Objectives:
Objectives:
In this lab, student will be able to:
1. Understand importance of light weight components and pluggable look-and-feel
2. Create, compile and run JavaFX applications
3. Know the fundamentals of event handling and role of layout managers
JavaFX:
JavaFX components are lightweight and events are handled in an easy-to-manage,
straightforward manner. The JavaFX framework is contained in packages that begin
with the javafx prefix. The packages we will use in our code are : javafx.application,
java. stage, javafx.scene, and javats.scene.layout.
The Stage and Scene Classes:
Stage is a top-level container. All JavaFX applications automatically have access to one
Stage, called the primary stage. The primary stage is supplied by the run-time system
when a JavaFX application is started.
Scene is a container for the items that comprise the scene. These can consist of controls,
such as push buttons and check boxes, text, and graphics, To create a scene, you will
add those elements to an instance of Scene.
Layouts:
JavaFX provides several layout panes that manage the process of placing elements in a
scene. For example, the FlowPane class provides a flow layout and the GridPane class
supports a row/column grid-based layout.
48The Application Class and Life-Cycle methods:
A JavaFX application must be a subelass of the Application class, which is packaged in
javafx.application. Thus, your application class will extend Application. The
Application class defines three life-cycle methods that your application can override.
1. void init() - The init( ) method is called when the application begins execution. It is
used to perform various initializations.
2. abstract void start(Stage primaryStage) - The start() method is called afier init( ).
This is where the application begins and it can be used to construct and set the scene.
This method is abstract and hence must be overridden by the application.
3. void stop()- When the application is terminated, the stop() method is called. It can
be used to handle any cleanup or shutdown chores.
Solved exercise:
1. Write a JavaFX Application program to display a simple message.
import javafx.scene.control.*;
import javafx.application. Application;
import javafx.stage. Stage;
import javafx.scene.Scene;
import javafx.scene.layout.*;
import javafx.scene.paint.Color,
public class HelloWorld extends Application {
public void start(Stage primaryStage) { _// entry point for the application
primaryStage.setTitle("Demo JavaFX Aplication"; / set the title of top level
Heontainer.
Label Ibl = new Label(); _(/ create a label control
Ibl.setText("Hello World from JavaFX");
IbL.setTextFill(Color. RED);
FlowPane root = new FlowPane(); // create a root node.
root.getChildren().add(Ibl);_// add the label to the node
Scene myScene ~ new Scene(root, 300, 50); // create a scene using the node
primaryStage.setScene(myScene); // set the scene on the stage
primaryStage.show(); // show the stage
49public static void main(String[] args) {
launch(args); // Start the JavaFX application by calling launch()
}
}
Output:
if) Demo JavaFX Aplication
Hello World from JavaFX
Event Handling:
The JavaFX controls that respond to either the extemal user input events or the internal
events need to be handled. The delegation event model is the mechanism of handling
such events. The advantage of this model is that application logic that processes the
events is cleanly separated from the User Interface logic that generates the event
Solved exercise:
2, Write a JavaFX-Application program that handles the event generated by Button
control,
im port javafx.application.*;
import javafx.scene.*,
import javafx.stage.*,
import javafx.scene lay out.*,
import javafx.scene.control.*,
import javafx.event.*,
import javafx.geometry.*,
public class JavaFXEventDemo extends Application {
Label response;
public static void main(String[] args) {
Jf Start the JavaFX application by calling launchQ)
Jaunch(args);
}
# Over de the start() method.
public void start(Stage myStage) (
50/I Give the stage a title.
myStage.setTitle("Use JavaFX Buttons and Events.”);
{Use a FlowPane for the root node. In this case,
JI vertical and horizontal gaps of 10.
FlowPane rootNode = new FlowPane(10, 10);
/f Center the controls in the scene.
rootNode.setAlignment(Pos. CENTER);
J} Create a scene.
Scene myScene = new Scene(rootNode, 300, 100);
if Set the scene on the stage.
myStage setScene(myScene);
if Create alabel.
response = new Label("Push a Button”);
if Create two push buttons.
Button binUp = new Button("Up");
Button btnDown = new Button("Down");
# Handle the action events for the Up bution.
binUp.setOnAction(new EventHandler() {
public void handle(ActionEvent ae) {
response.setText("You pressed Up."); } Ys
i Handle the action events for the Down button.
binDown.setOnA ction(new EventHandler() {
public void handle(ActionEvent ae) {
response.setText("You pressed Down."); } });
# Add the label and buttons to the scene graph.
rootNode.getChildren0.addAll(btnUp, binDown, response);
H Show the stage and its scene.
myStageshow(); } }
Output:
W) Use JavaFX Buttons and Events, =) 38
Up | [Down | You pressed Down,
SiLab exercises:
1, Write a JavaFX application program to do the foll owing
a, Display the message “Welcome to JavaFX programming” using Label in
the Scene
Set the text color of the Label to Magenta
Set the title of the Stage to “This is the first JavaFX Application”
Set the width and height of the Scene to $00 and 200 respectively,
Use FlowPane layout and set the hgap and vgap of the FlowPane to desired
values,
peas
2, Write JavaFX program to accept an integer from the user and display the
multiplication table (apto nmber * 10) for that number,
3. Write a JavaFX program to display a window as shown below, Use TextField
for UserName ad PasswordField for Password inputs. On click of “Sign in”
Button the message “Welcome UserName” should be displayed in a Text
Contral. Use Grid Layout for the application
wy JavaFX Welcome
Welcome
User Name: | Joshus
Paccword: | eeesee
Welcome Joshua | Sign in
Fig 11.1 Welcome Window
4, Write a JavaFX program that obtains two positive integers passed from the user
and displays the numbers and their GCD as the result,
Additional exercises:
1, Define a class called Employee with the attributes name, empID, desi gnation,
basiePay, DA, HRA, PF, LIC, netSalary. DA is40% of basicPay, HRA is 15%
of basicPay, PF is 12% of basicPay. Display all the employee information in a
JavaFX application
2, Design asimple calculator to show the working for simple arithmetic op erations.
Use Grid layout
32Lab No.: 12 Date:
JavaFX and Event Handling -Part IL
Objectives:
In this lab, student will be able to:
4. Explore JavaFX controls.
5. Understand the application of JavaFX controls in different programs.
6. Know the fundamentals of event handling.
JavaFX:
JavaFX provides a powerful, streamlined, flexible framework that simplifies the
creation of modem, visually exciting GUIs. The JavaFX framework has all of the good
features of Swing,
JavaFX control classes:
Button ListView TextField
‘CheckBox RadioButton ToggleButton
Label ScrollPane TreeView
© Button: Button is JavaFX’s class for push buttons. The procedure for adding an
image to a button is similar to that used to add an image to a label. First obtain
an Image View of the image. Then add it to the button.
« ListView: List views are controls that display a list of entries from which you
can select one or more.
«TextField: It allows one line of text to be entered. Thus, it is useful for obtaining,
names, ID strings, addresses, and the like. Like all text controls, TextField
inherits TextInputControl, which defines much of its functionality.
* CheckBos: It supports three states. The first two is checked or unchecked, as
you would expect, and this is the default behavior. The third state is
indeterminate (also called undefined). It is typically used to indicate that the
353state of the check box has not been set or that it is not relevant to a specific
situation, If you need the indeterminate state, you will need to explicitly enable
* RadioButton: Radio buttons are a group of mutually exclusive buttons, in which
only one button can be selected at any one time. They are supported by the
RadioButton class, which extends both ButtonBase and ToggleButton.
© ToggleButton: A toggle button looks just like a push button, but it acts
differently because it has two states: pushed and released. That is, when you
press a toggle button, it stays pressed rather than popping back up as a regular
push button does. When you press the toggle button a second time, it releases
(pops up).
© Label: Label class encapsulates a label. It can display a text message, a graphic,
or both.
© ScrollPane: JavaFX makes it easy to provide scrolling capabilities to any node in
ascene graph. This is accomplished by wrapping the node in a ScrollPane.
When a ScrollPane is used, scrollbars are automatically implemented that scroll
the contents of the wrapped node.
«= TreeView: It presents a hierarchical view of data in a tree-like format.
Solved exercise:
1. Write a JavaFX program to display an image in the Label.
import javafx.application.*;
import javafx.scene.*:
import javafx.stage.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;
import javafx.scene.image.*;
public class LabellmageDemo extends Application {
public static void main(String[] args) {
launch(args); __// Start the JavaFX application by calling launch(). —}
public void start(Stage myStage) { __// Override the start() method.
myStage.setTitle("Use an Image in a Label"), _// Give the stage a title.
FlowPane rootNode = new FlowPane(); _// Use a FlowPane for the root node.
34rootNode.setAlignment(Pos.CENTER): __// Use center alignment
Scene myScene = new Scene(rootNode, 300, 200); // Create a scene.
myStage.setScene(myScene); _// Set the scene on the stage.
// Create an ImageView that contains the specified image
Image View hourglassIV = new Image View("hourglass. png"
// Create a label that contains both an image and text.
Label hourglassLabel = new Label("Hourglass", hourglassIV);
rootNode.getChildren().add(hourglassLabel); // Add the label to the scene graph.
myStage.show(); // Show the stage and its scene. } }
Output:
Fig 12.1 Display an image in label
2. Write a JavaFX Application program that handles the event generated by a
Toggle Button.
import javafx.application.*;
import javafx.scene.*:
nport javafx.stage.*;
port javafx.scene.layout.*;
port javafx.scene.control.*;
import javafx.event.*
import javafx.geometry.*;public class ToggleButtonDemo extends Application {
ToggleButton thOnOff, Label response:
public static void main(String[] args) {
1 Start the JavaFX application by calling launch().
launch(args); }
public void start(Stage myStage) { _// Override the start() method.
myStage.setTitle("Demonstrate a Toggle Button"); _// Give the stage a title.
// Use a FlowPane for the root node. In this case, vertical and horizontal gaps of 10.
FlowPane rootNode = new FlowPane(10, 10);
/ Center the controls in the scene.
rootNode.set Alignment(Pos.CENTER),
Scene myScene = new Seene(rootNode, 220, 120), _/ Create a scene.
myStage.setScene(myScene), _// Set the scene on the stage.
response = new Label("Push the Button."); // Create a label.
tbOnOM = new ToggleButton("On/Ofl); _// Create the toggle button });
33
/J Handle action events for the toggle button.
thOnOff.setOnAction(new EventHandler() {
public void handle(ActionEvent ae) {
if(tbOnOff-isSelected())
response.setText("Button is on.");
else
response.setText("Button is off"); }});
1 Add the label and buttons to the scene graph.
rootNode. getChildren().add All(tbOnOff, response);
J Show the stage and its scene.
myStage.show(); } }
Output:Fig 12.2 Demonstration for toggle button
Lab Exercises:
1. Write a JavaFX application program that obtains two floating point numbers in two
text fields from the user and displays the sum, product, difference and quotient of
these numbers on clicking compute button with calculator image placed on it.
2. Write a JavaFX application program that allows the user to draw a rectangle by
dragging the mouse on the application window. The upper-left coordinate should be
the location where the user presses the mouse button, and the lower-right coordinate
should be the location where the user releases the mouse button. Also display the
area of the rectangle. Also modify the same program to draw a shape with the
mouse. The shape should be allowed to choose from an oval, an are, a line, a
rectangle with rounded comers and predefined polygon. Radio buttons must be
employed to display the shape options. Also display the mouse coordinates in the
status bar.
3. Write a JavaFX application program that creates a thread which will scroll the
message from right to left across the window or left to right based on checkbox
option selected by the user.
4, Write a JavaFX application program that displays a Circle of random size and
calculates and displays the area, radius, diameter and circumference in a Text Field
based on the option chosen in List View (Area or radius and so on).
Additional exercises:
1. Write a JavaFX program to simulate a static analog clock whose display is
controlled by a user controlled static digital clock.
2. Write a JavaFX program to implement a simple calculator using the Toggle buttons.
57REFERENCES
1.
Herbert Schildt and Dale Skrien, “Java Fundamentals — A Comprehensive
Introduction”, MeGrawHiill, 2015.
Herbert Schildt, “The Complete Reference JAVA Ninth Edition”, Tata McGrawHill,
2017.
Dietel and Dietel, “Java How to Program”, 9" Edition, Prentice Hall India, 2012.
Steven Holzner, “Java 2 programming BlackBook’ Dream Tech, India 2005.
38JAVA QUICK REFERENCE:
Class - A class can be defined as a template’ blue print that describe the
behaviours/states that object of its type support.
Methods - A method is basically behaviour. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables - Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.
Object - Objects have states and behaviours, Example: A dog has states-colour,
name, and breed as well as behaviours -wagging, barking, and eating, An object is
an instance of a class.
Case Sensitivity - Java is case sensitive which means identifier Hello and hello
would have different meaning in Java.
Class Names - For all class names the first letter preferred to be the Upper Case. If
several words are used to form a name of the class each inner words first letter
conventionally be in Upper Case, Example: class MyFirstJavaClass
Method Names - All method names preferably start with a Lower Case letter. If
several words are used to form the name of the method, then each inner word's first
letter conventionally be in Upper Case. Example: public void myMethodName( )
Program File Name - Name of the program file should exactly match the class
name. When saving the file, save it using the class name (Remember java is case
sensitive) and append ',java’ to the end of the name. (If the file name and the class
name do not match the program will not compile). Example: Assume
‘MyFirstJavaProgram’ is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
public static void main(String args[]) - java program processing starts from the
main() method which is a mandatory part of every java program.
Java Identifiers: All Java components require names. Names used for classes,
variables and methods are called identifiers. In java there are several points to
remember about identifiers. They are as follows:
39i) All identifiers should begin with a letter (A to Z or a to z ), currency character
(8) or an underscore (_).
ii) After the first character identifiers can have any combination of characters.
iii) A key word cannot be used as an identifier.
). Most importantly identifiers are case sensitive.
Examples of legal identifiers:age,Ssalary, value, __1_value
Examples of illegal identifiers :123abe, net-salary
= Java Modifiers:Like other languages, it is possible to modify classes, methods, ete.,
by using modifiers. There aretwo categories of modifiers.
i) Access Modifiers:default, publie , protected, private
ii) Non-access Modifiers:final, abstract
«Java Variable Types:
i) Local Variables
ii) Class Variables (Static Variables)
iii) Instance Variables (Non static variables)
= Java Arrays: Arrays are objects that store multiple variables of the same type.
However an Array itself is an object on the heap.
= Java Keywords: The following list shows the reserved words in Java. These
reserved words may not be used as constant or variable or any other identifier
names.
abstract [asset boolean [break byte [ease catch [Char [elas [const
continue | default Do ‘double else enum extends | Final finally | flaot
ior oto If implements [import [instance of |int _[interface| tong [native
new [package Private [protected [public [retum [short [static [ssricttp [super
switch [synchronized [This — [throw throws Jimansien’ [ty [Void [volatile [while
= Comments in Java: Java supports single line and multi-line comments very similar
to C++, Alll characters available inside any comment are ignored by Java compiler.
60Example 1:
/*This is my first java program.
* This will print ‘Hello World’ as the output
* This is an example of multi-line comments.
“/
Example 2:
/IThis is an example of single line comment
Data Types in Java: There are two categories of data types available in Java:
i) Primitive Data Types: There are eight primitive data types supported by Java.
Primitive data types are predefined by the language and named by a key word.
‘They are: byte, short, int, long, float, double, Boolean, char
ii) Reference/Object Data Types: Reference variables are created using defined
constructors of the classes. They are used to access objects. These variables
are declared to be of a specific type that cannot be changed. Examples:
Employee, Puppy etc. Class objects, and various type of array variables come
under reference data type. Default value of any reference variable is null. A
reference variable can be used to refer to any object of the declared type or any
compatible type.
iii) Example :Animal animal = new Animal("giraffe");
Java Literals: A literal is a source code representation of a fixed value. They are
represented directly in the code without any computation.
terals can be assigned to
any primitive type variable, For example: byte a= 68; char a="A’;
String literals in Java are specified like they are in most other languages by
enclosing a sequence of characters between a pair of double quotes. Examples of
string literals are:"Hello World", "two\nlines", "\"This is in quotes\""
Java language supports few special escape sequences for String and char literals as
well. Theyare:
Notation Characterrepresented
\n Newline (0x0a)
\v Carriage return (0x0d)
\t Formfeed (0x0c)
61\b Backspace (0x08)
\s Space (0x20)
\t tab
ig Double quote
v Single quote
Wu backslash
\dddOctal character (ddd)
\uxxxx Hexadecimal UNICODE character (xxx)
Java Access Modifiers: Java provides a number of access modifiers to set access
levels for classes, variables, methods and constructors. The four access levels are:
i) Visible to the package; the default; No modifiers are needed
ii) Visible to the class only (private)
sible to the world (public)
iv) Visible to the package and all subclasses (protected)
Branch Structures: The syntax ofif, Ise.if...else if...else, Nested if...else.switeh-
case, break,andcontinuestatements is similar to that of C++.
Loop Structures: The syntax ofwhile, do..while, andforstatements is similar to
that of C++, Java also provides enhancedforloop. This is mainly used for arrays and
collections.
for(declaration : expression)
#Statements
Java Basic Operators: Java provides a rich set of operators to manipulate
variables. The important Java operators with their precedence and associativity are
shown below.
62Category
Postfix
Unary
Muttiplicative
Additive
Shift
Relational
Equality
Bitwise AND
Bitwise XOR
Bitwise OR
Logical AND
Logical OR
Conditional
Assignment
Comma
Operator
(1). (dot operator)
tHeetH
1%
+-
>> >>> <<
>>pe<