Java Unit 1
Java Unit 1
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java was designed to be easy for a professional programmer to learn and use
effectively.
It’s simple and easy to learn if you already know the basic concepts of Object
Oriented Programming.
Best of all, if you are an experienced C++ programmer, moving to Java will
require very little effort. Because Java inherits the C/C++ syntax and many of
the object-oriented features of C++, most programmers have little trouble
learning Java.
Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
Object Oriented
Java is a true object-oriented programming language.
Almost the “Everything is an Object” paradigm. All program code and data
reside within objects and classes.
The object model in Java is simple and easy to extend.
Java comes with an extensive set of classes, arranged in packages that can be
used in our programs through inheritance.
Object-oriented programming (OOPs) is a methodology that simplifies
software development and maintenance by providing some rules.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Distributed
Java is designed to create distributed applications on networks.
Java applications can access remote objects on the Internet as easily as they
can do in the local system.
Java enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.
Java is designed for the distributed environment of the Internet because it
handles TCP/IP protocols.
Robust
It provides many features that make the program execute reliably in a variety
of environments.
Java is a strictly typed language. It checks code both at compile time and
runtime.
Java takes care of all memory management problems with garbage collection.
Java, with the help of exception handling, captures all types of serious errors
and eliminates any risk of crashing the system.
Secure
Java provides a “firewall” between a networked application and your
computer.
When a Java Compatible Web browser is used, downloading can be done
safely without fear of viral infection or malicious intent.
Java achieves this protection by confining a Java program to the Java
execution environment and not allowing it to access other parts of the
computer.
7. Architecture Neutral
Java language and Java Virtual Machine helped in achieving the goal of “write
once; run anywhere, any time, forever.”
Changes and upgrades in operating systems, processors and system resources
will not force any changes in Java Programs.
Portable
Java Provides a way to download programs dynamically to all the various
types of platforms connected to the Internet.
Java is portable because of the Java Virtual Machine (JVM). The JVM is an
abstract computing machine that provides a runtime environment for Java
programs to execute. The JVM provides a consistent environment for Java
programs to run on, regardless of the underlying hardware and operating
system. This means that a Java program can be written on one device and run
on any other device with a JVM installed, without any changes or
modifications.
9. High Performance
Java performance is high because of the use of bytecode.
The bytecode was used so that it can be easily translated into native machine
code
Multithreaded
Multithreaded Programs handled multiple tasks simultaneously, which was
helpful in creating interactive, networked programs.
Java run-time system comes with tools that support multiprocess
synchronization used to construct smoothly interactive systems.
Dynamic
Java is capable of linking in new class libraries, methods, and objects.
Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at runtime.
This makes it possible to dynamically link code in a safe and expedient
manner.
To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.
finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in
Object class as:
1. Instance Variables
2. Class Variables
3. Local Variables
Local Variables:
Local variables are those that are declared inside of a method, constructor, or code
block. Only the precise block in which they are defined is accessible. The local
variable exits the block's scope after it has been used, and its memory is freed.
Temporary data is stored in local variables, which are frequently initialised in the
block where they are declared. The Java compiler throws an error if a local variable is
not initialised before being used. The range of local variables is the smallest of all the
different variable types.
Example:
public SumExample
{
public void calculateSum() {
int a = 5; // local variable
int b = 10; // local variable
int sum = a + b;
System.out.println("The sum is: " + sum);
} // a, b, and sum go out of scope here
}
Output:
Example:
Example:
Method Parameters:
Variables that are supplied to a method when it is invoked are known as method
parameters. They serve as inputs for method execution and are used to receive
values from the caller. The scope of method parameters is restricted to the method
in which they are defined, making them local to that method. The values of the
arguments given are allocated to the respective parameters when a method is called.
Example:
public void printName(String name) { // name is a method parameter
System.out.println("Hello, " + name + "!");
}
Writing clear and effective Java code requires a solid understanding of variable
scope. Here are some essential ideas to bear in mind:
The minimal scope necessary for variables to serve their purpose should be
expressed. As a result, there are fewer naming conflicts, and the code is easier to
comprehend.
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It
can also be used in place of "int" data type.
The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example:
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:
Example:
1. float f1 = 234.5f
Example:
1. double d1 = 12.3
Method Description
codePointBefore() Returns the Unicode of the character before the specified ind
equals() Compares two strings. Returns true if the strings are equal, a
getBytes() Encodes this String into a sequence of bytes using the named
the result into a new byte array
offsetByCodePoints() Returns the index within this String that is offset from the giv
codePointOffset code points
replace() Searches a string for a specified value, and returns a new str
specified values are replaced
replaceAll() Replaces each substring of this string that matches the given
with the given replacement
Every time an object is created using the new() keyword, at least one constructor is
called.
1) Method overloading is used to increase the readability of the Method overriding is used
program. implementation of the me
provided by its super class
4) Method overloading is the example of compile time polymorphism. Method overriding is the
polymorphism.
5) In java, method overloading can't be performed by changing return Return type must be s
type of the method only. Return type can be same or different in method overriding.
method overloading. But you must have to change the parameter.
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString {
public static void main(String[] args)
{
String input = "Geeks for Geeks";
Palindrome
class PalindromeExample{
public static void main(String args[]){
int r,sum=0,temp;
int n=454;//It is the number variable to be checked for palindrome
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
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:
There are two types of Java programs — Java Stand-Alone Applications and Java Applets.
Java Applets
Java applets are Java applications that run within a web browser. They are mainly used for
internet programming. The applet is capable of performing many tasks on a web page, such
as displaying graphics, playing sounds, and accepting user input
Java Tokens
In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation. These
statements and expressions are made up of tokens. In other words, we can say that
the expression and statement is a set of tokens. The tokens are the small building
blocks of a Java program that are meaningful to the Java compiler. Further, these two
components contain variables, constants, and operators. In this section, we will
discuss what is tokens in Java.
Types of Tokens
Java token includes the following:
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
w
01. abstract 02. boolean 03. byte 04. break 05. class
06. case 07. catch 08. char 09. continue 10. default
21. import 22. instanceof 23. int 24. interface 25. long
26. native 27. new 28. package 29. private 30. protected
31. public 32. return 33. short 34. static 35. super
36. switch 37. synchronized 38. this 39. thro 40. throws
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier: Identifiers are used to name a variable, constant, function, class, and array.
It usually defined by the user. It uses letters, underscores, or a dollar sign as the first
character. The label is also known as a special kind of identifier that is used in the
goto statement. Remember that the identifier name must be different from the
reserved keywords. There are some rules to declare identifiers are:
Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is
defined by the programmer. Once it has been defined cannot be changed. Java provides five
types of literals are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Operators: In programming, operators are the special symbol that tells the compiler
to perform a special operation. Java provides different types of operators that can be
classified according to the functionality they provide. There are eight types
of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
Java operators are symbols that are used to perform operations on variables and manipulate the values
of the operands. Each operator performs specific operations. Let us consider an expression 5 + 1 = 6;
here, 5 and 1 are operands, and the symbol + (plus) is called the operator. We will also learn about
operator precedence and operator associativity.
The bitwise & operator always checks both conditions whether first condition is true
or false.
Output:
false
false