0% found this document useful (0 votes)
3 views12 pages

Corejava

The document provides an overview of key concepts in Java programming, including inheritance, constructors, arrays, method overloading and overriding, and object-oriented programming principles. It explains the differences between String and StringBuffer, layout managers, and the use of 'this()' and 'super()' in constructors. Additionally, it includes code examples for various concepts and operations such as copying files, displaying indoor and outdoor games, and calculating the transpose of a matrix.

Uploaded by

tayil98300
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

Corejava

The document provides an overview of key concepts in Java programming, including inheritance, constructors, arrays, method overloading and overriding, and object-oriented programming principles. It explains the differences between String and StringBuffer, layout managers, and the use of 'this()' and 'super()' in constructors. Additionally, it includes code examples for various concepts and operations such as copying files, displaying indoor and outdoor games, and calculating the transpose of a matrix.

Uploaded by

tayil98300
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is Inheritance?

Inheritance is an object-oriented programming concept where one class (child/subclass) acquires the properties and
behaviors (fields and methods) of another class (parent/superclass).

Why do we use inheritance?

To reuse code

To avoid duplication

To improve maintainability

To implement polymorphis

class Parent {
void display() {
[Link]("This is Parent class");
}
}

class Child extends Parent {


void show() {
[Link]("This is Child class");
}
}

public class Test {


public static void main(String[] args) {
Child obj = new Child();
[Link](); // inherited method
[Link]();
}
}

Types of Inheritance in Java


Type Description Supported in Java?
Single inheritance One child inherits one parent ✔ Yes
Multilevel inheritance Child → Parent → Grandparent chain ✔ Yes
Hierarchical inheritance Multiple children share same parent ✔ Yes
Multiple inheritance One child inherits multiple parents ❌ Not with classes (only via interfaces)
Hybrid inheritance Combination of two or more types ✔ Using interfaces

What is a Constructor?
A constructor is a special method in Java that is used to initialize objects.
Its name must be the same as the class name and it does not have any return type, not even void.

When is a constructor called?

A constructor is called automatically when an object of the class is created.

class Student {
Student() { // constructor
[Link]("Constructor Called");
}

public static void main(String[] args) {


Student obj = new Student(); // object creation
}
}

Types of Constructors in Java


Type Description
Default Constructor Created automatically by Java if no constructor is defined
No-Argument Constructor Constructor with no parameters
Parameterized Constructor Constructor with parameters (arguments)
Copy Constructor Copies values from one object to another (manually created in Java)

Array in Java is a data structure in Java used to store multiple values of the same data type
in a single variable. It occupies a continuous memory block, and elements are accessed
using index numbers starting from 0.

Syntax:
datatype[] arrayName = new datatype[size];

Example:
int[] numbers = new int[5];
int[] num = {10, 20, 30, 40, 50};

1. Arrays store only similar data [Link] size is fixed and cannot be changed. [Link] index begins from 0 to
length-1. [Link] are stored in sequential memory locations.

Types of Arrays in Java:

1. One-Dimensional Array [Link]-Dimensional Array [Link] Array [Link]-Dimensional Array Example:

public class Test {


public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};

for(int i = 0; i < [Link]; i++) { [Link](arr[i]); }

}
}

2. Two-Dimensional Array Example:


int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};

for(int i = 0; i < [Link]; i++) {


for(int j = 0; j < matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}

3. Jagged Array Example:


int[][] arr = {
{1, 2},
{3, 4, 5},
{6}
};

Array Operations:
Access element: arr[2]
Modify element: arr[1] = 100
Length of array: [Link]

Enhanced For Loop:


for(int x : arr) {
[Link](x);
}

Advantages: Easy to access elements using index. [Link] manage multiple values with one variable.

Disadvantages: Fixed size. [Link] stores same data type.

METHOD OVERLOADING IN JAVA

Method overloading is a feature in Java that allows a class to have more than one method with the same name but
different parameter lists. It increases the readability of the program and is an example of compile-time polymorphism.

1. Methods must have the same name. [Link] lists must be different in type, number, or order. [Link] type
can be same or different, but it does not play a role in overloading. [Link] is resolved at compile time, so it is also
known as compile-time polymorphism.

Example 1:
class Addition {
void add(int a, int b) {
[Link](a + b);
}

void add(int a, int b, int c) { [Link](a + b + c); }

public class Test {


public static void main(String[] args) {
Addition obj = new Addition();
[Link](10, 20);
[Link](10, 20, 30);
}
}

Why use Method Overloading?

1. Improves code [Link] duplication. [Link] the program clean and easy to understand.

Ways to overload methods:

1. By changing number of parameters [Link] changing data types of parameters [Link] changing order of parameters

Not allowed:
Method overloading cannot be done by changing only the return type without changing parameter list.

Method overriding is a feature in Java that allows a subclass to provide its own implementation of a method that is
already defined in its parent class. It is used to achieve runtime polymorphism.

1. Same parameter list and return type. [Link] have inheritance (extends keyword). [Link] at runtime, so it is
also known as runtime polymorphism. [Link] modifier of overridden method in child should be equal or more
accessible than parent. [Link], private, and final methods cannot be overridden.

Example:
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
[Link]("Dog barks");
}
}

public class Test {


public static void main(String[] args) {
Animal a = new Dog();
[Link]();
}
}

Output:
Dog barks

Why use Method Overriding?

1. To provide specific implementation in subclass. [Link] runtime polymorphism. [Link] achieve flexibility and
extensibility in object-oriented programming.

Rules for Method Overriding:

1. Method must be inherited from parent class. [Link] method signature: name + parameters. [Link] type must
be same or covariant. [Link] override private, static, or final methods. [Link] @Override annotation is
recommended (not mandatory).

Difference between Method Overloading and Method Overriding:


Method Overloading:

Occurs within the same class.

Different parameters.

Compile-time polymorphism.

Method Overriding:

Occurs between parent and child class.

Same parameters.

Runtime polymorphism.

OOP CONCEPTS IN JAVA

Object-Oriented Programming (OOP) is a programming approach based on real-world objects. It focuses on data and
behavior together, helping to build modular, reusable, and maintainable software.

OOP revolves around four main principles:

1. Encapsulation [Link] [Link] [Link]

Additional supporting concepts include:


Class, Object, Method, Constructor, Interface, Package, and Message Passing.

1. Encapsulation
Encapsulation is the process of binding data (variables) and methods together into a single unit called a class. It
protects data by restricting direct access using private variables and public getter/setter methods.

Example:
class Student {
private int age;

public void setAge(int a) { age = a; } public int getAge() { return age; }

2. Inheritance
Inheritance allows one class (child class) to acquire properties and methods of another class (parent class). It
supports code reusability and hierarchical structure.

Syntax:
class Child extends Parent { }

Types of inheritance:
Single, Multilevel, Hierarchical, Multiple (using interfaces), Hybrid.

3. Polymorphism
Polymorphism means the ability to take many forms. A single action can behave differently based on the object.

Types of Polymorphism:

1. Compile-time polymorphism: Achieved using Method Overloading.

2. Runtime polymorphism: Achieved using Method Overriding.

Example:
Animal a = new Dog();
[Link]();

4. Abstraction
Abstraction hides internal implementation and shows only essential features to the user. Implemented using
Abstract Classes and Interfaces.

Example:
abstract class Animal {
abstract void sound();
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

Class and Object


Class: A blueprint or template for creating objects. It contains data members and methods.
Object: An instance of a class that represents real-world entities and accesses class members.

Example:
class Car {
void drive() {
[Link]("Car is driving");
}
}

public class Test {


public static void main(String[] args) {
Car c = new Car();
[Link]();
}
}

Benefits of OOP

1. Code reusability through inheritance. [Link] security through encapsulation. [Link] and dynamic method
behavior using polymorphism. [Link] development and maintenance. [Link]-world modeling using objects.

Real Life Example of OOP Concepts


Example: Car

Encapsulation: Engine is hidden internally.

Inheritance: SportsCar inherits from Car.

Polymorphism: drive() works differently for different car types.

Abstraction: User only presses start button, internal working is hidden.

STRING IN JAVA String in Java is an object that represents a sequence of characters. It is immutable, meaning once
a String object is created, it cannot be changed.

Syntax:
String s = "Hello";
String s1 = new String("Java");

Properties of String: [Link] (cannot be modified) [Link] in the String Constant Pool [Link] in performance
when fewer modifications occur [Link] efficient for constant values

Example:
String s = "Hello";
s = [Link](" Java");
[Link](s);

Note: concat() creates a new String object because String is immutable.

STRINGBUFFER IN JAVA StringBuffer is a mutable class used to create modifiable string objects. It allows changes
like append, insert, delete without creating a new object.

Syntax:
StringBuffer sb = new StringBuffer("Hello");

Properties of StringBuffer: [Link] (changeable) [Link] and thread-safe [Link] compared to


StringBuilder due to thread safety

Example:
StringBuffer sb = new StringBuffer("Hello");
[Link](" Java");
[Link](sb);

Output:
Hello Java

DIFFERENCE BETWEEN STRING AND STRINGBUFFER

Feature String StringBuffer


Mutability Immutable Mutable
Thread Safety Not synchronized Synchronized (thread-safe)
Performance Faster for fewer modifications Slower due to thread safety
Feature String StringBuffer
Storage String Constant Pool Heap memory

When to Use What?

1. Use String when few modifications are required.

2. Use StringBuffer when frequent string changes are needed in a multithreading environment.

Short Example Showing Difference:


String s = "Java";
[Link](" Programming");
[Link](s);
// Output: Java (string does not change)

StringBuffer sb = new StringBuffer("Java");


[Link](" Programming");
[Link](sb);
// Output: Java Programming (changed)

LAYOUT MANAGER IN JAVA . A Layout Manager in Java is an object that controls the position and size of
components inside a container in GUI frameworks like AWT and Swing. It automatically arranges components based
on specific rules, without requiring manual positioning.

Purpose of Layout Manager:

1. To organize GUI components in a structured way. [Link] make GUI responsive across different screen sizes. [Link]
reduce manual use of setBounds() or absolute positioning.

Why Use Layout Manager?

1. Easy handling of component alignment. [Link] adjusts layout when window is resized. [Link]
interface consistent and user-friendly.

TYPES OF LAYOUT MANAGERS IN JAVA

1. FlowLayout
Arranges components in a row, left to right, and moves to next line when space is filled.
Example:
Frame f = new Frame();
[Link](new FlowLayout());

2. BorderLayout
Divides container into five regions: North, South, East, West, Center.
Example:
Frame f = new Frame();
[Link](new BorderLayout());

3. GridLayout
Arranges components in a rectangular grid of rows and columns.
Example:
Frame f = new Frame();
[Link](new GridLayout(2, 3));

4. GridBagLayout
Most flexible layout; allows components to span multiple rows and columns.

5. CardLayout
Allows switching between multiple components like cards (used in forms and wizard screens).

6. BoxLayout
Arranges components either vertically or horizontally.

Advantages:

1. Automatically manages component size and alignment. [Link] manual calculations. [Link] to
resizing.

Disadvantages:

1. Limited control over exact placement. [Link] layouts may require combination of multiple managers.

THIS() AND SUPER() IN CONSTRUCTORS IN JAVA

THIS() CONSTRUCTOR CALL this() is a special keyword used inside a constructor to call another constructor of the
same class. It helps in constructor chaining and reduces code duplication.

Rules of this():

1. Must be the first statement in a constructor. [Link] to call another constructor within the same class.

2. Cannot be used in a static context. [Link] in reusing code.

Example:
class Demo {
Demo() {
this(10);
[Link]("Default constructor");
}

Demo(int a) { [Link]("Parameterized constructor: " + a); }

public class Test {


public static void main(String[] args) {
Demo d = new Demo();
}
}

Output:
Parameterized constructor: 10
Default constructor

SUPER() CONSTRUCTOR CALL

super() is a keyword used to call the parent class constructor from the child class. It is useful to initialize parent class
properties before the child class initialization.

Rules of super():

1. Must be the first statement in a child class constructor. [Link] called if not written explicitly.

2. Used for constructor chaining between parent and child class.

Example:
class Parent {
Parent() {
[Link]("Parent constructor");
}
}

class Child extends Parent {


Child() {
super();
[Link]("Child constructor");
}
}

public class Test {


public static void main(String[] args) {
Child c = new Child();
}
}

Output:
Parent constructor
Child constructor

DIFFERENCE BETWEEN THIS() AND SUPER()

Feature this() super()


Purpose Calls another constructor of the same class Calls parent class constructor
Used in Constructor chaining within same class Constructor chaining in inheritance
Position Must be first statement Must be first statement
Relation Refers to current object Refers to parent object

copy file to another

import [Link].*;

public class CopyFile {


public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("[Link]");
FileOutputStream fout = new FileOutputStream("[Link]");

int i;
while ((i = [Link]()) != -1) {
[Link](i);
}

[Link]();
[Link]();

[Link]("File copied successfully");


} catch (Exception e) {
[Link](e);
}
}

package game;
public class Indoor {
public void display() {
[Link]("Indoor Games:");
[Link]("Chess");
[Link]("Carrom");
}
}

package game;
class Indoor {
String indoorGames[] = {"Chess", "Carrom", "Table Tennis"};

void showIndoor() {
[Link]("Indoor Games:");
for(String g : indoorGames) {
[Link](g);
}
}
}

class Outdoor {
String outdoorGames[] = {"Cricket", "Football", "Hockey"};

void showOutdoor() {
[Link]("Outdoor Games:");
for(String g : outdoorGames) {
[Link](g);
}
}
}

public class Result {


public static void main(String[] args) {
Indoor in = new Indoor();
Outdoor out = new Outdoor();

[Link]();
[Link]();
}
}

matrix and display its transpose

import [Link];

public class MatrixTranspose {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter number of rows: ");


int rows = [Link]();

[Link]("Enter number of columns: ");


int cols = [Link]();

int matrix[][] = new int[rows][cols];


int transpose[][] = new int[cols][rows];

// Input matrix elements


[Link]("Enter elements of matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = [Link]();
}
}

// Calculate transpose
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}

// Display transpose
[Link]("Transpose of Matrix:");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
[Link](transpose[i][j] + " ");
}
[Link]();
}

[Link]();
}
}

[op]Enter number of rows: 2


Enter number of columns: 3
Enter elements of matrix:
123
456

Transpose of Matrix:
14
25
36

File Class Methods in Java

The File class in Java ([Link]) is used to perform operations on files and directories like create, delete, check
existence, read properties etc.

Common Methods of File Class

Method Description
exists() Checks if file or directory exists.
createNewFile() Creates a new empty file.
mkdir() Creates a single directory.
mkdirs() Creates directory including required parent directories.
delete() Deletes a file or directory.
length() Returns size of file in bytes.
getName() Returns the name of file or directory.
getPath() Returns path of file/directory as given.
getAbsolutePath() Returns complete absolute file path.
isFile() Checks if path refers to a file.
isDirectory() Checks if path refers to a directory.
list() Returns list of files/directories inside folder.
renameTo(File f) Renames the file name.
canRead() Checks if file is readable.
canWrite() Checks if file is writable.
canExecute() Checks if file is executable.
Method Description
lastModified() Returns last modified date/time.

5 integers from command line

public class PrimeCheck {


public static void main(String[] args) {

if ([Link] < 5) {
[Link]("Please enter 5 integers as command line arguments.");
return;
}

for (int i = 0; i < 5; i++) {


int num = [Link](args[i]);
boolean isPrime = true;

if (num <= 1) {
isPrime = false;
} else {
for (int j = 2; j <= num / 2; j++) {
if (num % j == 0) {
isPrime = false;
break;
}
}
}

if (isPrime)
[Link](num + " is Prime");
else
[Link](num + " is Not Prime");
}
}
}

The <applet> tag in Java is an HTML tag used to embed a Java Applet program into a webpage. It allows Java code to
run inside a web browser. This tag was commonly used in older Java versions to display GUI elements, animations,
graphics, and interactive applications on web pages. However, the <applet> tag is deprecated in the latest versions
of Java and HTML due to security restrictions.

<applet code="[Link]" width="300" height="200">


</applet>

You might also like