JAVA PROGRAMMING
JAVA PROGRAMMING
By,
Dr.Vidya Rajasekaran
Skilling & Placement Coordinator
SPEC , Hyderabad.
1. Sample Java Program
First Java Program
// First Program End-of-line comment
package examples;
White space
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Training on Java Programming");
} // end method main End-of-line comment
} // end class HelloWorld End-of-line comment
Output
// First Program Single line comment / end-of-line comment.
/* My very first
Output:
Hello, world! This is on the same line.
3.2 System.out.println
public class PrintlnExample
{
public static void main(String[] args)
{
System.out.println("Hello, ");
System.out.println("world!");
System.out.println("This is on a new line.");
}
}
Output:
Hello,
world!
This is on a new line.
Difference between ‘System.out.print’ and
‘System.out.println’
System.out.print and System.out.println are methods used to
print messages to the console.
System.out.print System.out.println
Function: Prints the specified Function: Prints the specified message
message to the console. to the console.
Behavior: Does not append a Behavior: Appends a newline
newline character at the end of the character at the end of the message.
message.
Result: The cursor remains on the Result: The cursor moves to the
same line after printing the beginning of the next line after printing
message, so subsequent print the message, so subsequent print
statements will continue on the statements will appear on a new line.
same line.
Answer Me !
Hello, world!
This is on the same line. This is on a new line.
3.3 printf
System.out.printf(format, arguments);
3) %s: String
4) %c: Character
5) %b: Boolean
7) %n: Newline
Formatting Integers and Strings
public class PrintfExample
{
public static void main(String[] args)
{
String name = "Vidya";
int age = 35;
System.out.printf("Name: %s, %n Age: %d ", name, age);
}
}
Output:
Name: Vidya,
Age: 35
4. Escape Sequences in Java
Escape Sequences
line.
Output:
Hello,
world!
4.2 Tab (\t)
public class TabExample
{
public static void main(String[] args)
{
System.out.println("Hello,\t world!");
}
}
Output:
Hello, world!
Output:
He said, "Hello, world!"
4.4 Backslash (\\)
public class BackslashExample
{
public static void main(String[] args)
{
System.out.println("This is a backslash: \\");
}
}
Output:
This is a backslash: \
5. Common Syntax and Logical Error in
Java
Introduction
logical errors.
Example:
public class MismatchedBraces
{
public static void main(String[] args)
{
if (true)
{
System.out.println("This will cause an error");
}
Output:
This data type defines the kind of data the variable can hold, such as
methods.
Declaration and Initialization of Variables
Declaration:
int age; // Declaring an integer variable named age
double salary; // Declaring a double variable named salary
String name; // Declaring a String variable named name
Initialization:
age = 25; // Initializing the integer variable age with the value 25
salary = 50000.75; // Initializing the double variable salary with the
value 50000.75
name = "Alice"; // Initializing the String variable name with the value
"Alice"
Output:
Name: John Doe
Age: 25
Salary: 45000.5
7. Getting User Input in Java
Scanner Class
To interact with users and obtain input during the execution of a Java
program, you can use the Scanner class. The Scanner class provides
methods to read various types of input, such as strings, integers,
and doubles.
Steps to Get User Input Using the Scanner Class
Importing the Scanner Class:Before you can use the Scanner
class, you need to import it from the java.util package.
Creating a Scanner Object: Create an instance of the Scanner
class to read input from the standard input stream (usually the
keyboard).
Using Scanner Methods to Get Input: Use the methods
provided by the Scanner class to read different types of input.
Importing the Scanner Class
You need to import the Scanner class at the beginning of your Java
program:
import java.util.Scanner;
Creating a Scanner Object
Create an instance of the Scanner class:
Scanner scanner = new Scanner(System.in);
Scanner scanner = new Scanner(System.in); // Create a Scanner object to read input from the keyboard
Post-Decrement:
c: 5
c--: 5
c after c--: 4
Pre-Decrement:
d: 5
--d: 4
d after --d: 4
Answer Me!
public class IncrementDecrementExample {
public static void main(String[] args) {
int number = 10;
System.out.println("Original number: " + number);
number++;
System.out.println("After increment: " + number);
number--;
System.out.println("After decrement: " + number);
++number;
System.out.println(“First increment: " + number);
--number;
System.out.println(“First decrement: " + number);
}
}
Output
Original number: 10
After increment: 11
After decrement: 10
First increment: 11
First decrement: 10
12. Assignment Operators
Assignment Operators
Assignment operators are used to assign values to variables. Java provides several assignment operators to simplify
variable manipulation.
Syntax: Example:
case 'D':
case 'F':
System.out.println("Fail");
break;
default:
System.out.println("Invalid grade");
}
Default Case
//The default case in a switch statement executes when none of the other cases
match.
Syntax: Example:
Syntax: Example:
}
for (type variable : public class ForEachLoopExample {
collection) { public static void main(String[]
// code to be executed args) {
} int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println("Number:
" + num);
}
}
}
Key Points
for loop: Best when you know the number of iterations.
and return.
while (!isRunning) {
System.out.println("The system is not running.");
counter++;
if (counter == 3) {
isRunning = true;
}
}
System.out.println("The system is now running.");
}
}
4. Combining Logical Operators
Logical operators can be combined to create complex conditions that control the flow of
the program.
This means:
For &&: If the first condition is false, Java skips checking the
second condition because the whole expression is guaranteed to
be false.
For ||: If the first condition is true, Java skips checking the
second condition because the whole expression is guaranteed to
be true.
Example of short-circuiting with &&:
public class ShortCircuitExample {
public static void main(String[] args) {
int x = 5;
int y = 10;
Explanation: Since a < 10 is true, ++b > 10 is never evaluated, and b remains 10.
Summary
&& (AND): Executes the block only if all conditions are true.
|| (OR): Executes the block if at least one condition is true.
! (NOT): Reverses the boolean value of a condition.
Short-circuiting: Stops evaluating expressions as soon as the
result is determined.
These logical operators allow for more complex and flexible
control flows in loops and conditional statements, making your
code more powerful and efficient.
19. Nested Loops
20. Common Pitfalls and Best Practices
21. Debugging Control Flow Issues
OOPS
Classes and Objects
Class:
A class is a group of objects which have common properties.
Example: Public Class Animal
Object:
An Object can be defined as an instance of a class. Any entity that
has state and behavior is known as an object.
Example: A dog is an object because it has states like color,
name, breed, etc. as well as behaviors like wagging the tail,
barking, eating, etc.
Inheritance
Inheritance allows a new class (often called a
subclass or derived class) to inherit
properties and behaviors (fields and methods) Super
from an existing class (referred to as a super
class or base class). Class
Superclass and Subclass:
Superclass (Base Class):The class whose
properties and methods are inherited by
another class.
Subclass (Derived Class):The class that Derived
inherits properties and methods from
another class. Class
Types of Inheritance
1) Single Inheritance: In single inheritance, a subclass inherits from
only one superclass. Most object-oriented languages, like Java,
support single inheritance.
2) Multiple Inheritance: Multiple inheritance allows a subclass to
inherit from more than one superclass. Java does not support
multiple inheritance with classes to avoid complexity and ambiguity
(known as the "Diamond Problem").
3) Hierarchical Inheritance: Hierarchical inheritance occurs when
multiple subclasses inherit from a single superclass.
4) Multilevel Inheritance: In multilevel inheritance, a class is
derived from another derived class, forming a chain of
inheritance.
5) Hybrid Inheritance: Hybrid inheritance is a combination of
two or more types of inheritance. Java can support hybrid
inheritance using interfaces.
1. Single Inheritance
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method from Animal class
myDog.bark(); // Method from Dog class
}}
Superclass (Animal): The Animal class contains the method eat,
which is inherited by the Dog class.
Subclass (Dog): The Dog class inherits from the Animal class. This
means Dog has access to the eat method defined in Animal.
Method Calls:
myDog.eat(); - This line calls the eat method inherited from the Animal
class. Because Dog now inherits from Animal, this method is available to
the Dog class.
myDog.bark(); - This line calls the bark method that is specific to the
Dog class.
The Dog class needs to extend the Animal class to inherit its methods. Once
this inheritance relationship is correctly established using the extends
keyword, Dog can call methods from both the Dog class and the Animal
class, demonstrating the concept of inheritance in Java.
2. Multiple Inheritance
interface Animal {
void eat();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
public void eat() {
System.out.println("Dog eats.");
}
public void play() {
System.out.println("Dog plays.");
} }
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.play();
} }
Interfaces:
An interface in Java is a reference type, similar to a class, that
can contain only constants, method signatures, default
methods, static methods, and nested types.
Method Inheritance:
The Dog class inherits the eat() method from Animal and the
breathe() method from Mammal, in addition to having its own bark()
method.
This means that the Dog object (myDog) can use methods from all
the classes in the inheritance chain.
Benefits of Inheritance
Reusability: Inheritance allows the reuse of existing code,
reducing redundancy.
Extensibility: It is easy to add new features or modify existing
behavior by extending a class.
Modularity: Enhances code organization by allowing a clear
hierarchical structure.
Polymorphism: Inheritance allows the implementation of
polymorphism, making the code more flexible and reusable.
Costs of Inheritance
Complexity: Deep inheritance hierarchies can make code more
complex and harder to understand.
Tight Coupling: Subclasses are tightly coupled to their superclass,
which can make changes in the superclass affect the subclass.
Fragility: Over-reliance on inheritance can lead to fragile base class
problems, where changes to the base class can inadvertently break
the subclasses.
Overhead: Inheritance can introduce unnecessary overhead if not
used appropriately, especially if subclasses inherit methods or
properties they do not need.
When to Use Inheritance
IS-A Relationship: Inheritance is best used when there is a
clear IS-A relationship between the superclass and subclass.
For example, a Dog IS-A Animal.
Code Reusability: When you want to reuse existing code
and extend its functionality.
Polymorphism:When you need polymorphic behavior,
where a single interface can represent multiple underlying
forms (classes).
When to Avoid Inheritance
HAS-A Relationship: If the relationship between classes is
more of a HAS-A relationship, composition (where one class
contains objects of another class) may be a better approach.
Unnecessary Overriding: If the subclass does not need to
override or extend the functionality of the superclass
significantly, inheritance might not be the right tool.
Tight Coupling: If there is a risk of tight coupling between
the superclass and subclass, consider using interfaces or
composition.
Polymorphism
Polymorphism allows objects of different classes to be treated as
objects of a common superclass.
The word "polymorphism" comes from the Greek words "poly,"
meaning many, and "morph," meaning form, thus referring to
the ability to take on multiple forms.
It enables a single function, method, or operator to work in
different ways depending on the context.
Types of Polymorphism
Polymorphism in OOP can be broadly categorized into two types:
Accessors (Getters) and Mutators (Setters): Instead of directly accessing the fields
of a class, encapsulation provides methods (getters and setters) to read or modify the
values of private variables. This ensures that any modification of the data can be
controlled and validated.