Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Core Java Unit 1

This document discusses the history of Java and its key features. It provides details on the origins and development of Java from 1991 to present. The main topics covered include the history of Java, features like being simple, object-oriented, platform independent, secure, robust, architecture-neutral, portable and high-performance.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Core Java Unit 1

This document discusses the history of Java and its key features. It provides details on the origins and development of Java from 1991 to present. The main topics covered include the history of Java, features like being simple, object-oriented, platform independent, secure, robust, architecture-neutral, portable and high-performance.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

SHREE ADARSH BCA COLLEGE - HADADAD

BCA SEM - VI

SUBJECT – 604 Core Java

Unit - 1

Unit – 1 Introduction to Java


TOPIC – 1 History of java, Features of Java, Applications of Java,
Java Virtual Machine (JVM) and Byte Code, Buzzwords.
TOPIC – 2 Basic OOP Concepts- Abstraction, Encapsulation,
Inheritance and Polymorphism.
TOPIC – 3 Comparisons Between C++ and Java.
TOPIC – 4 Data types, Operators.
TOPIC – 5 Control Statements, Arrays and Command Line Arguments.
TOPIC – 6 Structure of Java Programming.

Prepared By:- Bhavesh Mehta


(bdmehta3300@gmail.com)

1
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java

TOPIC – 1
History of java, Features of Java, Applications of Java, Java Virtual Machine (JVM)
and Byte Code, Buzzwords.

Introduction to java
Java is a blend of the best elements of its rich heritage combined with the innovative concepts
required by its unique mission.
Java has become inseparably linked with the online environment of the Internet
Computer language innovation and development occurs for two fundamental reasons:
o To adapt to changing environments and uses
o To implement refinements and improvements in the art of programming
The development of Java was driven by both elements in nearly equal measure.
Java is related to C++, which is a direct descendant of C, Java is inherited from these two
languages. From C, Java derives its syntax.
Java was deeply rooted in the process of refinement and adaptation that has been occurringin
computer programming languages for the past several decades.
The development of Java was driven by both elements in nearly equal measure.

History of Java:

Java is a general-purpose, object-oriented programming language developed by Sun


Microsystem in 1991.
It is originally called “Oak” by James Gosling, one of the inventors of the language.
Java was designed for the development of software for consumer electronic devices like TV,
VCR-DVD, Washing Machine, and Refrigerator.
The Java team which included Patrick Naughton discovered that the existing language like C
and C++ had limitations in terms of both reliability and portability.
They modelled their new language Java on C and C++ but removed some features of C and C++
that were considered as sources of problems.
In 1990, Sun Microsystems decided to develop special software that could be used to
manipulate consumer electronic devices. A team of Sun Microsystems programmers headed
by James Gosling was formed to undertake this task.
In 1991, after exploring the possibility of using the most popular object-oriented language
C++, the team announced a new language named “Oak”.
In 1992, The team, known as Green Project team by Sun.
In 1993, The World Wide Web appeared on the Internet and transformed the text-based
Internet into a graphical environment.
In 1994, The team developed a Web browser called “HotJava” to locate and run applet
programs on internet.
In 1995, Oak was renamed “Java”, due to some legal snags. Java is just a name and is not an
acronym.
In 1996, Java established itself not only as a leader for Internet programming but also general-
purpose.
In 1997, Sun release Java Development Kit 1.1 (JDK 1.1)
In 1998, Sun releases Java 2 with version 1.2 of the Software Development Kit (SDK 1.2,
In 1999, Sun releases Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition (J2EE).
In 2000, J2SE with SDK 1.3 was released.
In 2002, J2SE with SDK 1.4 was released.
In 2004, J2SE with JDK 5.0 was released.

PREPARED BY: Bhavesh Mehta Page 2 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java

Features of Java OR Buzzwords of Java

The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role in
the popularity of this language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.

Simple
o Java is very easy to learn, and its syntax is simple, clean and easy to understand. According
to Sun Microsystem, Java language is a simple programming language because:
 Java syntax is based on C++ (so easier for programmers to learn it after C++).
 Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
 There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

Object-oriented
o Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior
o Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
o Basic concepts of OOPs are:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Platform Independent

PREPARED BY: Bhavesh Mehta Page 3 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
o Java is platform independent because it is
different from other languages like C, C++,
etc. which are compiled into platform
specific machines while Java is a write
once, run anywhere language. A platform is
the hardware or software environment in
which a program runs.
o There are two types of platforms software-
based and hardware-based. Java provides
a software-based platform.
o The Java platform differs from most other
platforms in the sense that it is a software-
based platform that runs on top of other
hardware-based platforms. It has two
components:
 Runtime Environment
 API(Application Programming Interface)
o Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
Secured
o Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
 No explicit pointer
 Java Programs run inside a virtual machine sandbox

 Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which
is used to load Java classes into the Java Virtual Machine dynamically. It adds security by
separating the package for the classes of the local file system from those that are
imported from network sources.
 Bytecode Verifier: It checks the code fragments for illegal code that can violate access
rights to objects.
 Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.

PREPARED BY: Bhavesh Mehta Page 4 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
o Java language provides these securities by default. Some security can also be provided by
an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
o The English mining of Robust is strong. Java is robust because:
 It uses strong memory management.
 There is a lack of pointers that avoids security problems.
 Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
 There are exception handling and the type checking mechanism in Java. All these points
make Java robust.
Architecture-neutral
o Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
o In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both
32 and 64-bit architectures in Java.
Portable
o Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
High-performance
o Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.
Distributed
o Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Multi-threaded
o A thread is like a separate program, executing concurrently. We can write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common
memory area. Threads are important for multi-media, Web applications, etc.
Dynamic
o Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.

Applications of Java
There are many places where Java is used in real world, starting from commercial e-commerce
website to android apps, from scientific application to financial applications like electronic trading
systems, from games like Minecraft to desktop applications like Eclipse, Netbeans and IntelliJ, from
open source library to J2ME apps etc.
Let's see each of them in more detail.
Android Apps
o If you want to see where Java is used, you are not too far away. Open your Android phone
and any app, they are actually written in Java programming language. Today many Java
programmer are Android App developer. By the way android uses different JVM and
different packaging,
Server Apps at Financial Services Industry
PREPARED BY: Bhavesh Mehta Page 5 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
o Java is very big in Financial Services. Lots of global Investment banks like Goldman Sachs,
Citigroup, Barclays, Standard Charted and other banks use Java for writing front and back
office electronic trading system, writing settlement and confirmation systems, data
processing projects and several others.
Java Web applications
o Java is also big on E commerce and web application space. You have a lot of RESTfull
services being created using Spring MVC, Struts 2.0 and similar frameworks.
Software Tools
o Many useful software and development tools are written and developed in Java e.g. Eclipse,
InetelliJ Idea and Netbans IDE.
Trading Application
o Third party trading application, which is also part of bigger financial services industry, also
use Java. Popular trading application like Murex, which is used in many banks for front to
bank connectivity, is also written in Java.
J2ME Apps
o All games, application, which is available in Android are written using MIDP and CLDC, part
of J2ME platform. J2ME is still popular on products likes Blu-ray, Cards, Set top boxes etc.
One of the reason of WhatsApp being so popular is because it is also available in J2ME for
all those Nokia handset which is still quite big.
Embedded Space
o Java is also big in the embedded space. It shows how capable the platform is, you only need
130 KB to be able to use Java technology (on a smart card or sensor). Originally Java was
designed for embedded devices.
High Frequency Trading Space
o Java platform has improved its performance characteristics a lot and with modern JITs, its
capable of delivering performance at C++ level. Due to this reason, Java is also popular on
writing high performance systems.
Scientific Applications
o Nowadays Java is often a default choice for scientific applications, including natural
language processing. Main reason of this is because Java is more safe, portable,
maintainable and comes with better high-level concurrency tools than C++ or any other
language.

Java Virtual Machine (JVM):

Introduction:
o Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the Java
Code or applications. It converts Java bytecode into machines language. JVM is a part of Java
Runtime Environment (JRE). In other programming languages, the compiler produces machine
code for a particular system. However, Java compiler produces code for a Virtual Machine
known as Java Virtual Machine.
o The JVM performs following operation:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JVM Architecture

PREPARED BY: Bhavesh Mehta Page 6 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
o Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.

o Classloader
 Classloader is a subsystem of JVM which is used to load class files. Whenever we run the
java program, it is loaded first by the classloader. There are three built-in classloaders in
Java.
 Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes, java.util
package classes, java.io package classes, java.sql package classes etc.
 Extension ClassLoader: This is the child classloader of Bootstrap and parent
classloader of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
 System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory. You can change the classpath using "-cp" or "-classpath" switch. It
is also known as Application classloader.
o Class(Method) Area
 Class(Method) Area stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.
o Heap
 It is the runtime data area in which objects are allocated.
o Stack
 Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.
 Each thread has a private JVM stack, created at the same time as thread.
 A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.
o Program Counter Register
 PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.
o Native Method Stack
 It contains all the native methods used in the application.
PREPARED BY: Bhavesh Mehta Page 7 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
o Execution Engine
 It contains:
 A virtual processor
 Interpreter: Read bytecode stream then execute the instructions.
 Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts
of the byte code that have similar functionality at the same time, and hence reduces
the amount of time needed for compilation. Here, the term "compiler" refers to a
translator from the instruction set of a Java virtual machine (JVM) to the instruction
set of a specific CPU.
o Java Native Interface
 Java Native Interface (JNI) is a framework which provides an interface to communicate
with another application written in another language like C, C++, Assembly etc. Java
uses JNI framework to send output to the Console or interact with OS libraries.

Bytecode
Bytecode is nothing but the intermediate representation of Java source code which is produced
by the Java compiler by compiling that source code.
This byte code is an machine independent code.
It is not an completely a compiled code but it is an intermediate code somewhere in the middle
which is later interpreted and executed by JVM.Bytecode is a machine code for JVM.
But the machine code is platform specific whereas bytecode is platform independent that is the
main difference between them.
It is stored in .class file which is created after compiling the source code.
Most developers although have never seen byte code.
One way to view the byte code is to compile your class and then open the .class file in a hex
editor and translate the bytecodes by referring to the virtual machine specification.
A much easier way is to utilize the command-line utility javap. The Java SDK from Sun includes
the javap disassembler, that will convert the byte codes into human-readable mnemonics.

An example of bytecode is shown below


Let us take a sample program.A Main class is created with login function

SOURCE CODE:
import java.io.*;
class Main
{
public static void main(String args[])

PREPARED BY: Bhavesh Mehta Page 8 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
{
new Login();
}
}
In command prompt compile it by typing "javac Main.java".
After that type "javap -c Main".You will get the byte code as follows

BYTE CODE:
Compiled from "Main.java"
class Main extends java.lang.Object{
Main();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return

public static void main(java.lang.String[]);


Code:
0: new #2; //class Login
3: dup
4: invokespecial #3; //Method Login."":()V
7: pop
8: return

}
The "javap -c" command disassembles a class file.
Disassembling done by Disassembler which converts machine language to assembly language.

TOPIC – 2
Basic OOP Concepts: Abstraction, Encapsulation, Inheritance and
Polymorphism.

Programming paradigm that views a computer program as a combination of objects which can
exchange information in a standardized manner, and can be combined with one another as
modules or blocks.
Each object is independent, can run by itself, and can be interlocked with other objects.
Objects interact by passing information among each other, and each object contains information
about itself and the objects it can interact with.
Major OOP-oriented languages are C++, Java, and Smalltalk.
Our definition of object oriented programming is : “Object oriented programming is an approach
that provided a way of modularizing programs by creating partitioned memory area for both
data and functions that can be used as templates for creating copies of such modules on demand.
The major objective of object oriented approach is to eliminate some of the flaws encountered in
the procedural approach.
Concepts:
Encapsulation:
The wrapping up of data and methods into a single unit is known as encapsulation.
Data encapsulation is the most striking feature of a class.

PREPARED BY: Bhavesh Mehta Page 9 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
The data is not accessible to the outside world and only those methods, which are wrapped in
the class, can access it.
These methods provide the interface between the object’s data the program.
This insulation of the data form direct access by the program is called data hiding.
Encapsulation makes it possible for objects to be treated like black box.

Abstraction:
Abstraction is the act of representing essential features without including the background
details or explanation.
Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, weight and cost, and methods that operate on these attributes.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
Inheritance supports the concept of hierarchical classification.
For example, the bird robin is a part of the class flying bird, which is again a part of the class
bird.
The concept of inheritance provides the idea of reusability.
This means that we can add additional features to an existing one.
The new class will have the combined features of both the classes.
Polymorphism:
Polymorphism in another important OOP concept.
Polymorphism means the ability to take more than one form.
For example, an operation may exhibit different behavior in different case. The behavior
depends upon the types of data used in the operation.
For example, consider the operation of addition for two numbers, the operation will generate
sum. If the operands are strings, then the operation would produce a third string by
concatenation.
Polymorphism plays an important role in allowing objects having different internal structures
to share the same external interface.
This means that that a general class of operations may be accessed in the same manner even
though specific actions associated with each operation may differ.
Polymorphism is extensively used in implementing inheritance.

TOPIC – 3
Comparisons Between C++ and Java.

Comparison Index C++ Java

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
Windows-based, web-based,
enterprise, and mobile applications.

Design Goal C++ was designed for systems and Java was designed and created as an
applications programming. It was interpreter for printing systems but
an extension of the C later extended as a support network
PREPARED BY: Bhavesh Mehta Page 10 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
programming language. computing. It was designed to be
easy to use and accessible to a
broader audience.

Goto C++ supports the goto statement. Java doesn't support the goto
statement.

Multiple C++ supports multiple inheritance. Java doesn't support multiple


inheritance inheritance through class. It can be
achieved by using interfaces in java.

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You can Java supports pointer internally.
write a pointer program in C++. However, you can't write the
pointer program in java. It means
java has restricted pointer support
in java.

Compiler and C++ uses compiler only. C++ is Java uses both compiler and
Interpreter compiled and run using the interpreter. Java source code is
compiler which converts source converted into bytecode at
code into machine code so, C++ is compilation time. The interpreter
platform dependent. executes this bytecode at runtime
and produces output. Java is
interpreted that is why it is
platform-independent.

Call by Value and C++ supports both call by value Java supports call by value only.
Call by reference and call by reference. There is no call by reference in java.

Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.

Thread Support C++ doesn't have built-in support Java has built-in thread support.
for threads. It relies on third-party
libraries for thread support.

Documentation C++ doesn't support Java supports documentation


comment documentation comments. comment (/** ... */) to create
documentation for java source code.

Virtual Keyword C++ supports virtual keyword so Java has no virtual keyword. We can
that we can decide whether or not override all non-static methods by
to override a function. default. In other words, non-static
methods are virtual by default.

unsigned right shift C++ doesn't support >>> operator. Java supports unsigned right shift
>>> >>> operator that fills zero at the
top for the negative numbers. For

PREPARED BY: Bhavesh Mehta Page 11 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
positive numbers, it works same
like >> operator.

Inheritance Tree C++ always creates a new Java always uses a single
inheritance tree. inheritance tree because all classes
are the child of the Object class in
Java. The Object class is the root of
the inheritance tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with


hardware.

Object-oriented C++ is an object-oriented language. Java is also an object-


However, in the C language, a oriented language. However,
single root hierarchy is not everything (except fundamental
possible. types) is an object in Java. It is a
single root hierarchy as everything
gets derived from java.lang.Object.

TOPIC -4 Data types, Operators

Data types in java:

You may remember two data types already, these being floating point (represented by the float
keyword) and integer (represented by the int keyword).
Java has eight different data types, all of which represent different kinds of values in a program.
These data types are byte, short, int, long, float, double, char, and boolean.
Integer Types
The most common values used in computer programs are integers, which represent whole
number values such as 12, 1988, and -34. Integer values can be both positive or negative, or
even the value 0.
The size of the value that's allowed depends on the integer data type you choose.
Java features four integer data types, which are byte, short, int, and long.
Byte
The first integer type, byte, takes up the least amount of space in a computer's memory.
When you declare a constant or variable as byte, you are limited to values in the range -128 to
127.
In Java, you declare a byte value like this:
byte identifier;
In the preceding line, byte is the data type for the value, and identifier is the variable's name.
You can also simultaneously declare and assign a value to a variable like this:
byte count = 100;
Short
The next biggest type of Java integer is short. A variable declared as short can hold a value from
-32,768 to 32,767.
You declare a short value like this: short identifier; OR short identifier = value;
In the preceding line, value can be any value from -32,768 to 32,767, as described previously.
In Java, short values are twice as big in memory-16 bits (or two bytes)-as byte values.
Int

PREPARED BY: Bhavesh Mehta Page 12 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
Next in the integer data types is int, which can hold a value from -2,147,483,648 to
2,147,483,647. Now you're getting into some big numbers.
The int data type can hold such large numbers because it takes up 32 bits (four bytes) of
computer memory.
You declare int values like this: int identifier; OR int identifier = value;
Long
The final integer data type in the Java language is long, which takes up a whopping 64 bits
(eight bytes) of computer memory and can hold truly immense numbers.
Unless you're calculating the number of molecules in the universe, you don't even have to
know how big a long number can be.
You declare a long value like this: long identifier; OR long identifier = value;
Floating-Point Types
Whereas integer values can hold only whole numbers, the floating-point data types can hold
values with both whole number and fractional parts.
Examples of floating-point values include 32.9, 123.284, and -43.436.
As you can see, just like integers, floating-point values can be either positive or negative.
Java includes two floating-point types, which are float and double.
Float
In Java, a value declared as float can hold a number in the range from around -3.402823 x 10
38 to around 3.402823 x 10 38.
These types of values are also known as single-precision floating-point numbers and take up
32 bits (four bytes) of memory.
You declare a single-precision floating-point number like this:
float identifier; OR float identifier = value;
Double
The second type of floating-point data, double, represents a double-precision value, which is a
much more accurate representation of floating-point numbers.
Because it allows for more decimal places.
A double value can be in the range from -1.79769313486232 x 10 308 to 1.79769313486232 x
10 308 and is declared like this: double identifier; OR double identifier = value;
Characters
Often in your programs, you'll need a way to represent character values rather than just
numbers.
A character is a symbol that's used in text. The most obvious examples of characters are the
letters of the alphabet, in both upper- and lowercase varieties.
There are, however, many other characters, including not only things such as spaces,
exclamation points, and commas, but also tabs, carriage returns, and line feeds.
The symbols 0 through 9 are also characters when they're not being used in mathematical
calculations.
In order to provide storage for character values, Java features the char data type, which is 16
bits.
However, the size of the char data type has little to do with the values it can hold. Basically, you
can think of a char as being able to hold a single character.
You declare a char value like this: char c; OR char c = 'A';
Boolean
Many times in a program, you need a way to determine if a specific condition has been met.
For example, you might need to know whether a part of your program executed properly.
In such cases, you can use Boolean values, which are represented in Java by the boolean data
type.
Boolean values are unique in that they can be only one of two possible values: true or false.
You declare a boolean value like this: boolean identifier; OR boolean identifier = value;
PREPARED BY: Bhavesh Mehta Page 13 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
In the second example, value must be true or false. In an actual program, you might write
something like this: booleanfile_okay = true;
Ex :-
classdatatype
{
public static void main(String args[])
{
// integer
byte a = 127;
short b = 32767;
int c = 2147483647;
long d = 1234567L;
// floating points
float e = 3.4f;
double f = 0.000000987;
// character type
char g = 'a';
// boolean type
boolean h = a>b;

System.out.println("------DATA TYPES------");
System.out.println("byte: "+a);
System.out.println("short: "+b);
System.out.println("int: "+c);
System.out.println("long: "+d);
System.out.println("float: "+e);
System.out.println("double: "+f);
System.out.println("char: "+g);
System.out.println("boolean: "+h);
}
}
O/P
byte: 127
short: 32767
int: 2147483647
long: 1234567
float: 3.4
double: 9.87E-7
char: a
boolean: false

Java Operators:

(1) Arithmetic Operators :


The Java programming language supports various arithmetic operators for all floating-point
and integer numbers.
These operators are + (addition), - (subtraction), * (multiplication), /(division), and %
(modulo).
The following table summarizes the binary arithmetic operations in the Java programming
language.
Operator Use Description
PREPARED BY: Bhavesh Mehta Page 14 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
+ op1 + op2 Adds op1 and op2
- op1 - op2 Subtracts op2 from op1
* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% Op1% op2 Computes remainder of dividing op1 by op2
Ex :-
classArithmaticOp
{
public static void main(String args[])
{
int a=10,b=5;
System.out.println("sum = "+(a+b));
System.out.println("sub = "+(a-b));
System.out.println("mul = "+(a*b));
System.out.println("div = "+(a/b));
System.out.println("mod = "+(a%b));
}
}
Output :
sum = 15
mul = 5
sum = 50
mul = 2
mul = 0

(2) Relational Operator:


A relational operator compares two values and determines therelationship between them.
For example, != returns true if the two operands are unequal. This table summarizes the
relational operators:
Operator Use Returns true if
> op1 > op2 op1 is greater than op2
>= op1 >= op2 op1 is greater than or equal to op2
< op1 < op2 op1 is less than op2
<= op1 <= op2 op1 is less than or equal to op2
== op1 == op2 op1 and op2 are equal
!= op1 != op2 op1 and op2 are not equal

Ex :-
classRelationalOp
{
public static void main(String args[])
{
int a=5,b=10,c=5;
System.out.println("a==b"+(a==b));
System.out.println("a!=b"+(a!=b));
System.out.println("a>b"+(a>b));
System.out.println("a<b"+(a<b));
System.out.println("a>=b"+(a>=b));
System.out.println("a<=b"+(a<=b));
}

PREPARED BY: Bhavesh Mehta Page 15 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
}
Output :
a==b false
a!=b true
a>b false
a<b true
a>=b false
a<=b true

(3) Assignment Operator:


The following table lists the shortcut assignment operators and their lengthy equivalents :
Operator Use Equivalent to
+= op1 += op2 op1 = op1 + op2
-= op1 -= op2 op1 = op1 - op2
*= op1 *= op2 op1 = op1 * op2
/= op1 /= op2 op1 = op1 / op2
%= op1 %= op2 op1 = op1 % op2

Ex :-
public class AssignmentOp
{
public static void main (String[] args)
{
int a=1,b=10;
a+=5;
b=b+5;
System.out.println(a);
System.out.println(b);
}
}
Output :
6
15
(4) Bitwise Logical Operator:
Operator Use Operation
& op1 & op2 Bitwise and
| op1 | op2 Bitwise or
^ op1 ^ op2 Bitwise xor
~ ~op2 Bitwise complement

Ex :-Bitwise logical operator using One Dim Array


classBitwiseLogicalOp
{
public static void main(String args[])
{
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3;

PREPARED BY: Bhavesh Mehta Page 16 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
int b = 6;
int c = a | b;
int d = a & b;
int e = a ^ b;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
}
}
Output :
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101

(5) Conditional or Ternary operator:


To find absolute (non-negative) value we used ternary operator.
Relational operators often are used with conditional operators to construct more complex
decision-making expressions.
The ?: operator is a conditional operator that is short-hand for an if-else statement:
op1 ?op2 : op3;
The ?: operator returns op2 if op1 is true or returns op3 if op1 is false.
Ex :-
public class TernaryOP
{
public static void main(Stringargs[])
{
Inti,ans;
i=-10;
ans=i<0?-i:i;
System.out.println("Absolute value of i = "+ans);
}
}

Output :
Absolute value of i = 10

(6) Increment and Decrement Operator:


The shortcut increment/decrement operators are summarized in the following table.
Operator Use Description
++ op++ Increments op by 1; evaluates to the value of op before it
was incremented
++ ++op Increments op by 1; evaluates to the value of opafter it was
incremented
-- op-- Decrements op by 1; evaluates to the value of op
before it was decremented
-- --op Decrements op by 1; evaluates to the value of op
after it was decremented
PREPARED BY: Bhavesh Mehta Page 17 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java

Ex :- Post and Pre increment operator


classIncreDecreOp
{
public static void main(String[] args)
{
int a=10,b=20;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("a++="+(a++));
System.out.println("++b="+(++b));
System.out.println("a="+a);
System.out.println("b="+b);
}
}
Output :
a=10
b=20
a++=10
++b=21
a=11
b=21
(7) Explain Bitwise Shift Operator:
A shift operator performs bit manipulation on data by shifting the bits of its first operand right
or left.
This table summarizes the shift operators available in the Java programming language.
Operator Use Operation
>> op1 >> op2 shift bits of op1 right by distance op2
<< op1 << op2 shift bits of op1 left by distance op2
>>> op1 >>> op2 shift bits of op1 right by distance op2(unsigned)
Ex :-
class Shift
{
public static void main (String args[])
{
int x = 7;
System.out.println("x = " + x);
System.out.println("x >> 2 = " + (x >> 2));
System.out.println("x << 1 = " + (x << 1));
System.out.println("x >>> 1 = " + (x >>> 1));
}
}
Output :
x=7
x >> 2 = 1
x << 1 = 14
x >>> 1 = 3

PREPARED BY: Bhavesh Mehta Page 18 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java

TOPIC – 5
Control Statements, Arrays and Command Line Arguments.

Control Statements:

Statement Type Keyword


Looping while, do-while , for
decision making if-else, switch-case
Branching break, continue, label:, return

(1) If … else
The If statement enables your program to selectively execute other statements, based on some
criteria.
This is the simplest version of the if…else statement: The block of statements will be executed
if a condition is true.
Generally, the simple form of if can be written like this:
if (expression)
{
True statement
}
else
{
False Statement
}
What if you want to perform a different set of statements if the expression is false? You use the
else.
The else block is executed if the if part is false. Another form of the else statement.
Class ifelse
{
public static void main(String arg[])
{
int a=10,b=20;
if(a>b)
{
System.out.println("a is greater than b");
}
else
{
System.out.println("b is greater than a");
}
}
}
Output :
b is greater than a
(2) Switch … case
statement to conditionally perform statements based on an integer expression.
Following is a sample program, SwitchDemo, that declares an integer named month whose
value supposedly represents the month in a date.

PREPARED BY: Bhavesh Mehta Page 19 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
The program displays the name of the month, based on the value of month, using the switch
statement:
Class SwitchDemo
{
public static void main(String[] args)
{
int month = 8;
switch (month)
{
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Hey, that's not a valid month!");
break;
}
}
}
Output:August

While loop
You use a while statement to continually execute a block of statements while a condition
remains true.
The general syntax of the while statement is:
while (expression)
{
Statement;
}
First, the while statement evaluates expression , which must return a boolean value.
If the expression returns true, then the while statement executes the statement(s) associated
with it.
The while statement continues testing the expression and executing its block until the
expression returns false.
Ex :-
public class While
{
public static void main(String[] args)
{
int i=5;
while(i>0)
{

System.out.println("i="+i);
PREPARED BY: Bhavesh Mehta Page 20 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
i--;
}
}
}

Output :
i=5
i=4
i=3
i=2
i=1
(3) do … while loop
The Java programming language provides another statement that is similar to the while
statement, the do-while statement.
The general syntax of the do-while is:
do
{
statement(s);
} while (expression);
Instead of evaluating the expression at the top of the loop, do-while evaluates the expression at
the bottom.
Thus the statements associated with a do-while are executed at least once.
Class dowhile
{
public static void main(String args[])
{
int i=5;
do
{
System.out.println("i="+i);
i--;
}while(i>0);
}
}
Output :
i=5
i=4
i=3
i=2
i=1
(4) for loop
The for statement provides a compact way to iterate over a range of values.
The general form of the for statement can be expressed like this:
for (initialization;condition;increment/decrement)
{
Statements;
}
The initialization is an expression that initializes the loop-it's executed once at the beginning of
the loop.
The conditional expression determines when to terminate the loop.
This expression is evaluated at the top of each iteration of the loop.
PREPARED BY: Bhavesh Mehta Page 21 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
When the expression evaluates to false, the loop terminates.
Finally, increment or decrement is an expression that gets invoked after each iteration through
the loop.
Ex :-
public class ForLoop
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
System.out.println("i="+i);
}
}
}
Output :
i=1
i=2
i=3
i=4
i=5
(5) Labeled Loop OR Outer Loop
A label is an identifier placed before a statement.
The label is followed by a colon (:).
The labeled form of the continue statement skips the current iteration of an outer loop marked
with the given label.
Ex :- Print only odd number between 1 to 10 using Label Loop or Outer Loop
Class LabelLoop
{
public static void main(String args[])
{
outer : for(int m=1;m<11;m++)
{
if(m%2==0)
{
continue outer;

}
else
{
System.out.println(m);
}
}

}
}
(6) Using Break- Exit from a Loop
By using break, you can force immediate termination of a loop, bypassing theconditional
expression and any remaining code in the body of the loop.
When a breakstatement is encountered inside a loop, the loop is terminated and program
controlresumes at the next statement following the loop.
Ex :-
PREPARED BY: Bhavesh Mehta Page 22 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
Class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++)
{
if(i == 6) break; // terminate loop if i is 6
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output :
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
Loop complete.
(7) Continue statement
You use the continue statement to skip the current iteration of a for, while , or do-while loop.
The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean
expression that controls the loop, basically skipping the remainder of this iteration of the loop.
Ex :-
class Continue
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
System.out.print(i+" ");
if(i%2==0) continue;
System.out.println();
}
}
}
Output :
01
23
45
67
89
(8) Return statement
The last of Java's branching statements is the return statement.
You use return to exit from the current method.
The flow of control returns to the statement that follows the original method call.
The return statement has two forms: one that returns a value and one that doesn't.
To return a value, simply put the value (or an expression that calculates the value)
o after the return keyword:
When a method is declared void, use the form of return that doesn't return a value.
PREPARED BY: Bhavesh Mehta Page 23 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
Ex :-
class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
Output :
Before the return.

Array in java

An array is a structure that holds multiple values of the same type.


The length of an array is established when the array is created (at runtime).
After creation, an array is a fixed-length structure.
An array element is one of the values within an array and is accessed by its position within the
array.
If you want to store data of different types in a single structure or if you need a structure
Arrays are objects that contain a number of variables of the same type.
These component variables are referenced using the integer indices 0,…,n-1, where nis the
length of the array.
The type of the array is identified by appending [] to the type of its components.
For example, int[] identifies an array of type int, Object[] identifies an array of type Object, and
char[][] identifies an array of type char.
Array Allocation
When a variable of an array type is declared, the size of the array is not identified, and the
array object is not allocated.
To allocate storage for an array, you can use the new operator to create an array object of
aspecific size. For example, the following statement:
Charch[] = new char[24];
Creates a char array of length 24, the individual component variables of which can be
referenced by ch[0], ch[2], …, ch[23].
The following statement creates an array of type Dice[] of length 6:
Dice[] d = new Dice[6];
Arrays can also be allocated by specifying their initial values.
For example, the following allocates a String array of length 7 that contains abbreviations for
the days of the week:
String days[] = {"sun", "mon", "tue", "wed", "thu", "fri", "sat"};
The length of an array can always be found by appending length to the name of the array.
For example, days.length returns the integer 7 as the length of days[].
Ex :- One Dim Array
classArr
{
public static void main(String args[])
{
Intmonth_day[]={31,28,31,30,31,30,31,31,30,31,30,31};
System.out.println("Days of April month are = "+month_day[3]);
PREPARED BY: Bhavesh Mehta Page 24 /30
SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
}
}

Output :
Days of April month are = 30

Command line arguments

Sometimes you will want to pass information into a program when you run it.
This isaccomplished by passing command-line arguments to main( ).
A command-line argument isthe information that directly follows the program’s name on the
command line when it isexecuted.
To access the command-line arguments inside a Java program is quite easy—they are stored as
strings in a String array passed to the args parameter of main( ).
The firstcommand-line argument is stored at args[0], the second at args[1], and so on.
For example,the following program displays all of the command-line arguments that it is called
with:
// Display all command-line arguments.
classCommandLine
{
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +
args[i]);
}
}
Try executing this program, as shown here:
JavaCommandLine this is a test 100 -1
When you do, you will see the following output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1

TOPIC – 6
Structure of Java Programming.

Java is an object-oriented programming, platform-independent, and secure programming


language that makes it popular. Using the Java programming language, we can develop a wide
variety of applications. So, before diving in depth, it is necessary to understand the basic
structure of Java program in detail. In this section, we have discussed the basic structure of a
Java program. At the end of this section, you will able to develop the Hello world Java program,
easily.

PREPARED BY: Bhavesh Mehta Page 25 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java

Let's see which elements are included in the structure of a Java program. A typical structure of
a Java program contains the following elements:
o Documentation Section
o The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program.
o The information includes the author's name, date of creation, version, program name,
company name, and description of the program.
o It improves the readability of the program. Whatever we write in the documentation
section, the Java compiler ignores the statements during the execution of the program.
o To write the statements in the documentation section, we use comments. The comments
may be single-line, multi-line, and documentation comments.
o Single-line Comment: It starts with a pair of forwarding slash (//). For example:
o Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols. For example:
o Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:
o Package Declaration
o The package declaration is optional. It is placed just after the documentation section. In
this section, we declare the package name in which the class is placed.
o Note that there can be only one package statement in a Java program. It must be defined
before any class and interface declaration. It is necessary because a Java class can be
placed in different packages and directories based on the module they are used.
o For all these classes package belongs to a single parent directory. We use the
keyword package to declare the package name. For example:
package javatpoint; //where javatpoint is the package name
package com.javatpoint; //where com is the root directory and javatpoint is the subdire
ctory

PREPARED BY: Bhavesh Mehta Page 26 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java

o Import Statements
o The package contains the many predefined classes and interfaces. If we want to use any
class of a particular package, we need to import that class.
o The import statement represents the class stored in the other package. We use
the import keyword to import the class. It is written before the class declaration and after
the package statement.
o We use the import statement in two ways, either import a specific class or import all
classes of a particular package. In a Java program, we can use multiple import statements.
For example:
import java.util.Scanner; //it imports the Scanner class only
import java.util.*; //it imports all the class of the java.util package

o Interface Section
o It is an optional section. We can create an interface in this section if required. We use
the interface keyword to create an interface. An interface is a slightly different from the
class.
o It contains only constants and method declarations. Another difference is that it cannot
be instantiated. We can use interface in classes by using the implements keyword.
o An interface can also be used with other interfaces by using the extends keyword. For
example:
interface car
{
void start();
void stop();
}

o Class Definition
o In this section, we define the class. It is vital part of a Java program. Without the class, we
cannot create any Java program.
o A Java program may conation more than one class definition. We use the class keyword to
define the class. The class is a blueprint of a Java program.
o It contains information about user-defined methods, variables, and constants. Every Java
program has at least one class that contains the main() method. For example:
class Student //class definition
{
}

o Class Variables and Variables


o In this section, we define variables and constants that are to be used later in the program.
In a Java program, the variables and constants are defined just after the class definition.
o The variables and constants store values of the parameters. It is used during the
execution of the program. We can also decide and define the scope of variables by using
the modifiers.
o It defines the life of the variables. For example:
class Student //class definition
{
String sname; //variable
int id;
double percentage;

PREPARED BY: Bhavesh Mehta Page 27 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
}

o Main Method Class


o In this section, we define the main() method. It is essential for all Java programs. Because
the execution of all Java programs starts from the main() method. In other words, it is an
entry point of the class.
o It must be inside the class. Inside the main method, we create objects and call the
methods. We use the following statement to define the main() method:
public class Student //class definition
{
public static void main(String args[])
{
//statements
}
}

o Methods and Behaviors


o In this section, we define the functionality of the program by using the methods. The
methods are the set of instructions that we want to perform. These instructions execute at
runtime and perform the specified task.

Procedure to run java program:


Start Notepad, In a new document, type in the following code:
/* The HelloWorldApp class implements an application that * displays "Hello World!" to the
standard output. */
public class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Save this code to a file. From the menu bar, select File > Save. In the Save As dialog box:
Using the Save in drop-down menu, specify the folder (directory) where you'll save your file.
In this example, the directory is java on the C drive. In the File name text box, type
"HelloWorldApp.java", including the double quotation marks. From the Save as type drop-
down menu, choose Text Document. When you're finished, the dialog box should look like this:

Now click Save, and exit NotePad.

PREPARED BY: Bhavesh Mehta Page 28 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
Compiling a program
To Compile the Source File :

From the Start menu, select the Command Prompt application (Windows XP). When the
application launches, it should look like this:
The prompt shows your current directory. When you bring up the prompt for Windows XP,
your current directory is usually WINDOWS on your C drive. To compile your source code file,
change your current directory to the directory where your file is located. For example, if your
source directory is java on the C drive, you would type the following command at the prompt
and pressEnter:

cd c:\java
Now the prompt should change to C:\java>.
If you enter dir at the prompt, you should see your file.

Now you can compile. At the prompt, type the following command and press Enter:

javac HelloWorldApp.java
The compiler has generated a Java bytecode file, HelloWorldApp.class. At the prompt, type dir
to see the new file that was generated:

PREPARED BY: Bhavesh Mehta Page 29 /30


SHREE ADARSH BCA COLLEGE - HADADAD
BCA SEM-VI Unit-1 604-Core Java
Now that you have a .class file, so you can run your program.

Running a program :
In the same directory, enter at the prompt: “java HelloWorldApp”

Finally, you get the output : Hello World!

PREPARED BY: Bhavesh Mehta Page 30 /30

You might also like