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

Unit 1 Java

The document provides an overview of Java programming concepts, including Java buzzwords, type casting, classes, methods, constructors, static keyword, 'this' keyword, string manipulation, decision-making statements, and method overloading/overriding. It explains each concept with definitions, syntax, and examples to illustrate their usage in Java. The content serves as a foundational guide for understanding key features and functionalities of the Java programming language.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit 1 Java

The document provides an overview of Java programming concepts, including Java buzzwords, type casting, classes, methods, constructors, static keyword, 'this' keyword, string manipulation, decision-making statements, and method overloading/overriding. It explains each concept with definitions, syntax, and examples to illustrate their usage in Java. The content serves as a foundational guide for understanding key features and functionalities of the Java programming language.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Unit – 1

1. List Java buzz words and explain about them


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  Architecture neutral


 Object-Oriented  High Performance
 Portable  Multithreaded
 Platform independent  Distributed
 Secured  Dynamic
 Robust
Simple

 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

 The English mining of Robust is strong. Java is robust because:


 It uses strong memory management.
 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

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).

2. What is Type casting? Explain with an example


Java provides various datatypes to store various data values.
Converting one primitive datatype into another is known as type casting (type conversion) in Java.
Syntax: <datatype> variableName = (<datatype>) value;

Types of Type Casting

 Widening Type Casting ( Implicit conversion)


 Narrowing Type Casting (Explicit conversion)

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.

3. What is class? Write a java simple program with Explanation.


Class: A class in Java is a blueprint from which individual objects are created. It is a prototype or template that defines
the properties and behaviors of the objects. In other words, a class is a user-defined data type that contains data and
methods.

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;
}

// Define a method to display car information


public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("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);

// Call the displayInfo method to show car information


myCar.displayInfo();
}
}

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

4. What is method? How to call a method in java with suitable example.


A method is a block of code that performs a specific task. Methods are commonly known as functions. In Java, a method
is declared inside a class. It can be called from anywhere in the program.

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();

// Call the method "sayHello" on the object


myObj.sayHello();
}
}
Explanation:
 In the above code, we define a class MyClass with a method sayHello() that prints "Hello, World!" to the console.
 In the Main class, we create an object myObj of MyClass using the new keyword.
 We then call the method sayHello() on the object myObj using the dot (.) notation.
Output:
Hello, World!

5. Define Constructor? Write a sample program for overloading constructors.


A constructor is a special type of method that is used to initialize objects. It is automatically called when an object is
created. Constructors can have different parameters, which allows you to initialize objects with different values.

Program for overloading constructors:


class Rectangle {
private double length;
private double width;

// Default constructor
public Rectangle() {
length = 0.0;
width = 0.0;
}

// Parameterized constructor with length and width parameters


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

public double calculateArea() {


return length * width;
}
}

public class Main {


public static void main(String[] args) {
// Creating objects using different constructors
Rectangle rectangle1 = new Rectangle(); // Default constructor
Rectangle rectangle2 = new Rectangle(5.0, 3.0); // Parameterized constructor

System.out.println("Area of Rectangle 1: " + rectangle1.calculateArea());


System.out.println("Area of Rectangle 2: " + rectangle2.calculateArea());
}
}
In this example:
 The Rectangle class has two constructors: a default constructor and a parameterized constructor that takes
length and width.
 We create instances of the Rectangle class using both constructors in the Main method.
 Then, we calculate and print the area of the rectangles created.
Output:
Area of Rectangle 1: 0.0
Area of Rectangle 2: 15.0

6. Explain about static with simple program.


The static keyword in Java is used for memory management mainly. We can apply static keyword with variables,
methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class.

Program:
public class StaticExample {
static int staticVariable = 10; // Static variable

static void printStaticVariable() { // Static method


System.out.println("Value of static variable: " + staticVariable);
}

public static void main(String[] args) {


printStaticVariable(); // Calling static method directly
}
}

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

7. Explain about this keyword with suitable example.


The this keyword in Java is a reserved keyword that refers to the current object. It can be used to access the instance
variables and methods of the current object. It is used to avoid naming conflicts between instance variables and
parameters.
Example:
class Car {
// Define instance variables
String brand;
String model;
int year;

public Car(String brand, String model, int year) {


this.brand = brand; //Using 'this' to refer to the instance variable
this.model = model; //Using 'this' to refer to the instance variable
this.year = year; //Using 'this' to refer to the instance variable
}

public void displayInfo() {


System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}

public class Main {


public static void main(String[] args) {
// Create an object of Car class
Car myCar = new Car("Ecosport", "Ford", 2018);

myCar.displayInfo();
}
}

Output:
Brand: Ecosport
Model: Ford
Year: 2018

8. What is String? Explain any five string class methods


String is an object that represents a sequence of characters. It is a widely used class in Java for working with textual
data. Strings in Java are immutable, meaning once created, their values cannot be changed. Any operation that
seems to modify a string actually creates a new string object with the modified value.

Five commonly used methods of the String class in Java:

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 statement: The if statement is used to execute a block of code if a condition is true.


The syntax is:
if (condition) {
// code to be executed if condition is true
}
Example:
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
}

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 Overloading and Method Overriding


Method Overloading:
Definition: Method overloading allows a class to have multiple methods with the same name but different parameter
lists.
Characteristics:
 Methods must have the same name but different parameter lists (different number, type, or order of
parameters).
 Return type may or may not be the same.
 Overloading can occur within the same class or between a superclass and its subclass.
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}

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");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

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.

You might also like