Unit 1 Java
Unit 1 Java
A list of the most important features of the Java language is given below.
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 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
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.
Platform Independent
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.
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because there is no
explicit pointer and Java Programs run inside a virtual machine sandbox.
Robust
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive
types is fixed.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code.
Distributed
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
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
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++.
Java supports dynamic compilation and automatic memory management (garbage collection).
Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the casting/conversion is
done automatically therefore, it is known as implicit type casting. In this case both datatypes should be compatible with
each other.
byte -> short -> char -> int -> long -> float -> double
Syntax: larger_data_type variable_name = smaller_data_type_variable;
Example:
int intValue = 10;
double doubleValue = intValue; // Implicit casting from int to double
System.out.println(doubleValue); // Output: 10.0
In this example, the integer value intValue is implicitly converted to a double value doubleValue. Since there's no loss of
data (both are numeric types), the conversion happens automatically.
Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the casting/conversion
is not done automatically, you need to convert explicitly using the cast operator “( )” explicitly. Therefore, it is known as
explicit type casting. In this case both datatypes need not be compatible with each other.
double -> float -> long -> int -> char -> short -> byte
syntax: smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;
Example:
double doubleValue = 10.5;
int intValue = (int) doubleValue; // Explicit casting from double to int
System.out.println(intValue); // Output: 10
In this example, the double value doubleValue is explicitly cast to an integer value intValue. Since integers cannot
represent fractional values, the fractional part of doubleValue is truncated, resulting in loss of data.
Syntax:
class ClassName [extends SuperClassName]
{
[member variables]
[class methods]
}
Program:
// Define a class named Car
class Car {
// Define instance variables
String brand;
String model;
int year;
// Define a constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
// Main class
public class Main {
public static void main(String[] args) {
// Create an object of Car class
Car myCar = new Car("Ecosport", "Ford", 2018);
In this program:
We define a class named Car with instance variables (brand, model, and year), a constructor to initialize these
variables, and a method displayInfo() to display car information.
In the Main class, we create an object myCar of the Car class using the new keyword and pass arguments to the
constructor to initialize its state.
We then call the displayInfo() method on the myCar object to display the car's information.
Output:
Brand: Ecosport
Model: Ford
Year: 2018
Syntax:
type MethodName (parameter-list)
{
Method-body;
}
Method Definition:
class MyClass {
public void sayHello() {
System.out.println("Hello, World!");
}
}
To call a method:
Write the method's name.
Follow it with two parentheses ().
Add a semicolon ( ; ).
If the method has parameters in the declaration, you can pass those parameters within the parentheses ().
Method call:
public class Main {
public static void main(String[] args) {
MyClass myObj = new MyClass();
// Default constructor
public Rectangle() {
length = 0.0;
width = 0.0;
}
Program:
public class StaticExample {
static int staticVariable = 10; // Static variable
Explanation:
In this program, staticVariable is a static variable declared within the StaticExample class.
The printStaticVariable() method is declared as static, allowing it to be called without creating an instance of the
class.
Inside the main method, we call the static method printStaticVariable() directly without creating an object of the
class.
When the program runs, it prints the value of the static variable.
Output:
Value of static variable: 10
myCar.displayInfo();
}
}
Output:
Brand: Ecosport
Model: Ford
Year: 2018
1. length(): This method returns the length of the string, i.e., the number of characters in the string.
Example:
String str = "Hello";
int length = str.length(); // length is 5
2. charAt(int index):This method returns the character at the specified index within the string. Indexing starts from 0.
Example:
String str = "Hello";
char ch = str.charAt(1); // ch is 'e'
3.substring(int beginIndex): This method returns a new string that is a substring of the original string, starting from the
specified index beginIndex to the end of the string.
Example:
String str = "Hello World";
String substr = str.substring(6); // substr is "World"
4. concat(String str):
This method concatenates the specified string to the end of the current string and returns a new string.
Example:
String str1 = "Hello";
String str2 = " World";
String result = str1.concat(str2); // Returns "Hello World"
5. equals(Object obj): This method compares the content of the current string with the specified object. It returns true if
the content of both strings is equal; otherwise, it returns false.
Example:
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2); // isEqual is true
-> Discuss various types of decision making and branching statements with syntax.
Various types of decision making and branching statements with syntax in Java:
if-else statement: The if-else statement is used to execute a block of code if a condition is true, and another block of
code if the condition is false.
The syntax is:
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example:
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is less than or equal to 5");
}
if-else-if ladder: The if-else-if ladder is used to execute one block of code from multiple statements.
The syntax is:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if all conditions are false
}
Example:
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else if (x < 15) {
System.out.println("x is less than 15");
} else {
System.out.println("x is less than or equal to 5");
}
switch statement: The switch statement is used to execute a block of code depending on the value of a variable.
The syntax is:
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
// More cases can be added as needed
default:
// Code to be executed if expression does not match any case
}
Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// More cases can be added for other days
default:
System.out.println("Invalid day");
}
Ternary Operator:
The ternary operator (condition) ? expression1 : expression2 is a shorthand way to write an if-else statement.
The syntax is:
result = (condition) ? expression1 : expression2;
Example:
int x = 10;
String message = (x > 5) ? "x is greater than 5" : "x is less than or equal to 5";
Method Overriding:
Definition: Method overriding occurs when a subclass provides a specific implementation for a method that is already
provided by its superclass.
Characteristics:
Method in the subclass must have the same name, parameter list, and return type as the method in the
superclass.
The method in the subclass must be marked with @Override annotation (optional but recommended).
Overriding occurs only in inheritance.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
Method overloading allows multiple methods with the same name but different parameter lists within the same class or
between a superclass and its subclass, while method overriding provides a way for a subclass to provide its own
implementation for a method inherited from its superclass, enabling polymorphic behavior.